Perl的(或和)和(||,&&)短路算子有什么区别? [英] What is the difference between Perl's ( or, and ) and ( ||, && ) short-circuit operators?
问题描述
这些子程序中的哪个子程序与其他子程序不同?
Which of these subroutines is not like the other?
sub or1 {
my ($a,$b) = @_;
return $a || $b;
}
sub or2 {
my ($a,$b) = @_;
$a || $b;
}
sub or3 {
my ($a,$b) = @_;
return $a or $b;
}
sub or4 {
my ($a,$b) = @_;
$a or $b;
}
我从C和Perl 4进入Perl 5,并一直使用||
,直到看到更多使用or
的脚本,并且我喜欢它的外观.但是,正如以上测验所示,对于那些粗心的人来说,这并非没有陷阱.对于同时使用这两种构造或经常使用or
的人们,您使用什么经验法则来决定使用哪种构造并确保代码在执行您认为正在做的事情?
I came to Perl 5 from C and Perl 4 and always used ||
until I saw more scripts using or
and I liked the way it looked. But as the above quiz shows, it's not without its pitfalls for the unwary. For people who use both constructs or who use a lot of or
, what rules of thumb do you use to decide which construct to use and make sure the code is doing what you think it is doing?
推荐答案
由于'or'运算符的优先级较低,因此or3解析如下:
Due to the low precedence of the 'or' operator, or3 parses as follows:
sub or3 {
my ($a,$b) = @_;
(return $a) or $b;
}
通常的建议是仅对控制流使用或"运算符:
The usual advice is to only use the 'or' operator for control flow:
@info = stat($file) or die;
有关更多讨论,请参见perl手册: http://perldoc.perl.org/perlop.html#Logical-or-and-Exclusive-Or
For more discussion, see the perl manual: http://perldoc.perl.org/perlop.html#Logical-or-and-Exclusive-Or
这篇关于Perl的(或和)和(||,&&)短路算子有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!