2014-11-20 64 views
0

我對邏輯運算符& &和||,或。的使用(以及返回值)我有些懷疑。在比較條件時使用邏輯運算符AND OR

$number = 5; 
$numberA = 5; 
$numberB = 1; 

$string = "x"; 
$stringA = "x"; 
$stringB = "y"; 

If two numbers are compared: 
$x=5; 
if ($x == $number) { print '$x == $number', "\n"; } 


If two strings are compared: 
$x="x"; 
if ($x eq $string) { print '$x eq $string', "\n"; } 

但我不知道什麼是評價兩個數字/字符串爲數字/字符串的最佳方式。它是否正確?

$x=5; $y=5; 
if (($x && $y) == $number) { print '($x && $y) == $number', "\n"; } 


$x="x"; $y="x"; 
if (($x and $y) eq $string) { print '($x and $y) eq $string', "\n"; } 

當兩個邏輯在相​​同條件下評估時,規則是什麼?應該將條件本身作爲數字進行比較(& &,||)或字符串(和或)?

$x=5; $y=1; 
if (($x == $numberA) && ($y == $numberB)) { print '&& or and here?', "\n"; } 

$x="x"; $y="y"; 
if (($x eq $stringA) and ($y eq $stringB)) { print 'and or or here?', "\n"; } 
+0

什麼是(5 && 5)給你? – 2014-11-20 23:57:28

回答

2
($foo && $bar) == $baz 

不會做你認爲它;它首先評估& &操作,如果$foo爲真則獲得$foo的值,否則獲得值$bar,然後將其與$baz進行比較。你需要明確地拼出它作爲$foo == $baz && $bar == $baz來測試兩者。

如果有多個值(優選在陣列中,而不是一個單獨的束的變量),可以grep的是有用的:

if (2 == grep $_ == $baz, $foo, $bar) { 

一覽:: MoreUtils提供了一種方便的方法all,得:

use List::MoreUtils 'all'; 
if (all { $_ == $baz } $foo, $bar) { 

and/or&&/||不是字符串或數字運算符;字母的功能與等效的符號完全相同。唯一的區別是它們有不同的優先級; &&/||具有更高的優先級,使得它們在內有用表達式; and/or具有較低的優先級,因此它們對於實質上不同表達式之間的流量控制很有用。一些例子:

my $x = $y || 'default_value'; 

等同於:

my $x = ($y || 'default_value'); 

my @a = get_lines() or die "expected some lines!"; 

等同於:

(my @a = get_lines()) or die "expected some lines!"; 
+0

很好的回答。我正在尋找這種類型的解釋。 – PedroA 2014-11-21 01:06:28