Perl 的(或、和)和(||、&&)短路运算符有什么区别?
这些子例程中哪一个与另一个不同?
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
的人,您使用什么经验法则来决定使用哪种构造并确保代码正在执行您认为正在执行的操作?
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;
}
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
由于 'or' 运算符的优先级较低,or3 解析如下:
通常的建议是仅使用 'or' 运算符进行控制流:
有关更多讨论,请参阅 perl 手册: http://perldoc.perl.org/perlop.html#Logical-or-and-Exclusive-Or
Due to the low precedence of the 'or' operator, or3 parses as follows:
The usual advice is to only use the 'or' operator for control flow:
For more discussion, see the perl manual: http://perldoc.perl.org/perlop.html#Logical-or-and-Exclusive-Or
运算符优先级规则。
||
紧密结合,或
弱结合。不存在“经验法则”。如果您必须有经验法则,那么“仅在没有左值时使用
or
”怎么样:or
:||
:我同意与 MJD 关于避免括号;如果您不知道规则,请查找它们...但不要编写
(open(my $fh, '>', 'file')) 或 (die("无法打开文件: $!"))
“只是为了确定”,请。The operator precedence rules.
||
binds tightly,or
binds weakly. There is no "rule of thumb".If you must have a rule of thumb, how about "only use
or
when there is no lvalue":or
:||
:I agree with MJD about avoiding parens; if you don't know the rules, look them up... but don't write
(open(my $fh, '>', 'file')) or (die("Failed to open file: $!"))
"just to be sure", please.在 Perl 5 中,“or”和“and”的优先级低于“||”和“&&”。查看此 PerlMonks 线程以获取更多信息:
http://www.perlmonks.org/?node_id=155804< /a>
In Perl 5, "or" and "and" have lower precedence than "||" and "&&". Check out this PerlMonks thread for more info:
http://www.perlmonks.org/?node_id=155804
这两个版本在 Perl 中都是短路的,但“文本”形式(“and”和“or”)的优先级低于其 C 风格等效形式。
http://www.sdsc.edu /~moreland/courses/IntroPerl/docs/manual/pod/perlop.html#Logical_And
Both versions are short-circuiting in Perl, but the 'textual' forms ('and' and 'or') have a lower precedence than their C-style equivalents.
http://www.sdsc.edu/~moreland/courses/IntroPerl/docs/manual/pod/perlop.html#Logical_And
我的猜测是 or3 是不同的。
我并不是真正的 Perl 爱好者,但看起来 1、2 和 4 都显式返回布尔值。我猜 3 有副作用,比如返回 $a 或类似的疯狂的东西。
低头
嘿,我是对的。
My guess is that or3 is different.
I'm not really a Perl guy, but it looks like 1, 2, and 4 all explicitly return booleans. I'm guessing 3 has side effects, such as returning $a or something crazy like that.
looks down
Hey, I was right.