gpt4 book ai didi

perl - 谁能解释一下 perl 程序的行为

转载 作者:行者123 更新时间:2023-12-04 22:46:37 25 4
gpt4 key购买 nike

$a="";
$b="n";
$c = !$a;
$d = !$b;
print $c , "\n" , $d;
if($d == 0){
print "zero";
}

我写了这个 perl 程序我希望输出如下
1  
0Zero

但它打印
1  
zero

谁能解释一下为什么会这样??

最佳答案

Perl 中的变量根据上下文被视为数字或字符串。如果你在赋值时没有把它当作一个数字,Perl 会在你打印它时把它当作一个字符串来对待。

因此,假值是 a bit different in Perl than in languages with stronger typing (重点是我加的):

The number 0, the strings '0' and "" , the empty list () , and undef are all false in a boolean context. All other values are true. Negation of a true value by ! or not returns a special false value. When evaluated as a string it is treated as "" , but as a number, it is treated as 0. Most Perl operators that return true or false behave this way.



所以,这里的问题是 !是逻辑运算符而不是算术运算符。因此,它返回一个逻辑上错误的值,该值根据上下文以不同的方式表示。

如果您想确保将某些内容视为数字,您有几个选择。您可以执行算术运算,这将使 Perl 将结果视为一个数字:
$d=!$b+0;
print $d;

您可以使用 sprintfprintf显式控制显示:
printf '%d', $d;

或者您可以使用 int :
print int $d;

(注意:这一切可能看起来有点复杂。但它的设计是为了让语言只做你想做的事,你不必考虑它。通常情况下确实如此。只有偶尔的边缘情况,你需要做一些 Perl 的默认行为以外的事情。)

关于perl - 谁能解释一下 perl 程序的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22704730/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com