Perl 的 ( or, and ) 和 ( ||, && ) 短路运算符有什么区别? [英] What is the difference between Perl's ( or, and ) and ( ||, && ) short-circuit operators?

查看:48
本文介绍了Perl 的 ( or, and ) 和 ( ||, && ) 短路运算符有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这些子程序中哪个与另一个不同?

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 的人,您使用什么经验法则来决定使用哪种结构并确保代码按照您的想法运行?>

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 的 ( or, and ) 和 ( ||, && ) 短路运算符有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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