2014-09-01 92 views
5

在其他语言中我会写为什么“x = a或b”在Perl中不起作用?

testvar = onecondition OR anothercondition; 

有,如果这两个条件中的testvar是真实的。但在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";} 

我本来希望$ res包含“1”,或者在用if()进行测试时证明是真的。但它包含空字符串。

我该如何在Perl中实现这个功能?周围表达

+4

检查出[运算符优先级表(HTTP: //perldoc.perl.org/perlop.html#Operator-Precedence-and-Associativity)。用'||'比较'或'。 – user2864740 2014-09-01 10:02:42

回答

19

穿戴括号,

my $res = ($cond1 or $cond2); 

,或者使用较高的优先级||操作者,

my $res = $cond1 || $cond2; 

作为代码由perl的解释为(my $res = $cond1) or $cond2;,或者更准确地说,

perl -MO=Deparse -e '$res = $cond1 or $cond2;' 
$cond2 unless $res = $cond1; 

如果您使用use warnings;它也会警告你关于$cond2

Useless use of a variable in void context 
+5

有趣的是,当人们对相反的问题抱怨时,''或'关键字被添加到了Perl中。 Perl 4只有'||',没有'或'。 – tripleee 2014-09-01 10:15:09

+0

我在我的代码中使用警告,并得到了警告。然而,在真实的代码中(不是这个测试代码),这些语句并没有像这里那样分裂,所以我从来没有在那里得到警告。而在此之上,我不明白它试图告诉我什么:)感谢您的彻底答案。 – jackthehipster 2014-09-01 10:19:21

+2

@jackthehipster'使用诊断;'对于警告将更具描述性。 – 2014-09-01 10:24:02

1

@jackthehipster:你所做的一切都是正确的只是把括号为$cond1 or $cond2如下图所示代码:

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";} 
相关问题