2014-09-01 33 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";} 
相關問題