0

我在 Perl 中有一些用于多个条件的代码

if (/abc/ && !/def/ && !/ghi/ && jkl) {

#### do something
}

是否会在每一行上一次评估每个条件?

我可以优先使用嵌套if的条件

if (/abc/){

  if (!/def/){

  ....so on

}
4

2 回答 2

2

&&短路。它仅在需要时评估其 RHS 操作数。如果它的 LHS 操作数返回一些错误,&&那么该值是否会返回。

例如,

use feature qw( say );
sub f1 { say "1"; 1 }
sub f2 { say "2"; 0 }
sub f3 { say "3"; 0 }
sub f4 { say "4"; 0 }
1 if f1() && f2() && f3() && f4();

输出:

1
2

所以下面两行基本相同:

if (/abc/) { if (!/def/) { ... } }

if (/abc/ && !/def/) { ... }

其实if编译成and操作符,所以上面很接近

(/abc/ and !/def/) and do { ... };

(/abc/ && !/def/) and do { ... };
于 2013-07-10T23:35:22.117 回答
1

不。

这样想,如果我说

"is the moon bigger than the sun?"
AND  "is the pacific bigger than the mediterraan?"
AND  "is russia bigger than england?"
AND  ... many more AND ....

您可以很快回答“否”,而不必弄清楚第一个问题以外的任何问题的答案。这叫“短路”

所以在你的情况下,除非输入行匹配

/abc/ && !/def/ && !/ghi/

您无需评估它是否匹配 /jkl/。

于 2013-07-11T04:22:40.960 回答