jac*_*ter 5 perl if-statement boolean operators
在其他语言中我会写
testvar = onecondition OR anothercondition;
Run Code Online (Sandbox Code Playgroud)
如果任何一个条件,testvar为true.但在Perl中,这并不像预期的那样有效.
我想检查一个内容变量为空或者与特定正则表达式匹配的情况.我有这个示例程序:
my $contents = "abcdefg\n";
my $criticalRegEx1 = qr/bcd/;
my $cond1 = ($contents eq "");
my $cond2 = ($contents =~ $criticalRegEx1);
my $res = $cond1 or $cond2;
if($res) {print "One or the other is true.\n";}
Run Code Online (Sandbox Code Playgroud)
我希望$ res包含"1"或者在用if()测试时可以证明为真.但它包含空字符串.
我怎样才能在Perl中实现这一目标?
Сух*_*й27 19
把括号括在表达式周围,
my $res = ($cond1 or $cond2);
Run Code Online (Sandbox Code Playgroud)
或使用更高优先级的||运算符,
my $res = $cond1 || $cond2;
Run Code Online (Sandbox Code Playgroud)
因为您的代码被perl解释为(my $res = $cond1) or $cond2;,或者更准确地说,
perl -MO=Deparse -e '$res = $cond1 or $cond2;'
$cond2 unless $res = $cond1;
Run Code Online (Sandbox Code Playgroud)
如果你使用use warnings;它也会警告你$cond2,
Useless use of a variable in void context
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
253 次 |
| 最近记录: |