$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@H_404_35@ are all false in a boolean context. All other values are true.@H_404_35@Negation of a true value by ! or not returns a special false value.@H_404_35@ When evaluated as a string it is treated as “”,but as a number,it@H_404_35@ is treated as 0. Most Perl operators that return true or false behave@H_404_35@ this way.
所以,这里的问题是!是一个逻辑运算符而不是算术运算符.因此,它返回逻辑假值,该值根据上下文以不同方式表示.
如果您想确保将某些内容视为数字,您可以选择一些选项.您可以执行算术运算,这将使Perl将结果视为一个数字:
$d=!$b+0; print $d;
您可以使用sprintf或printf显式控制显示:
printf '%d',$d;
或者你可以使用int:
print int $d;
(注意:这一切看起来有点复杂.但它的设计是为了让语言能够做你想要的,而且你不必考虑它.而且通常情况确实如此.只有你偶尔出现的边缘情况需要做除Perl默认行为之外的其他事情.)