Perl的&&结果是什么? [英] What is the result of Perl's &&?

查看:59
本文介绍了Perl的&&结果是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试此操作时:

$a = 1;
$b = 2;
print ($a && $b) . "\n";

结果是2.为什么?

推荐答案

引用 perlop :

"||","//"和&&"经营者 返回最后计算的值 (与C的"||"和&&"不同, 返回0或1).

The "||", "//" and "&&" operators return the last value evaluated (unlike C's "||" and "&&", which return 0 or 1).

Perl认为结果2为true,因此在逻辑条件下使用&&运算符时,一切都会按预期进行.额外的好处是您还可以在其他上下文中使用逻辑运算符:

The resulting 2 is considered true by Perl, so that when you use the && operator in a logical condition, everything works as expected. The added bonus is that you can use the logical operators in other contexts as well:

sub say_something {
    say shift || 'default';
}

say_something('foo'); # prints 'foo'
say_something(); # prints 'default'

甚至作为流量调节器:

my $param = shift || die "Need param!";
-f $file && say "File exists.";

在最后两个示例中,很高兴认识到,如果&&||运算符没有短路.如果您在第一行中输入shift为真值,则没有意义评估右侧(die…),因为整个表达式仍然为真.而且,如果文件测试在第二行失败,则您无需再次评估右侧,因为总体结果为假.如果逻辑运算符仍然坚持要对整个表达式求值,那么我们就不能以这种方式使用它们.

In the last two examples it’s good to realize that they could not work if the && and || operators did not short-circuit. If you shift a true value in on first line, there is no point evaluating the right side (die…), since the whole expression is true anyway. And if the file test fails on the second line, you don’t need to evaluate the right side again, since the overall result is false. If the logical operators insisted on evaluating the whole expression anyway, we could not use them this way.

这篇关于Perl的&&结果是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆