2009-07-16 109 views
29

C風格的運算符&&,|| ......和它們的Perl人類可讀版本「and」,「or」,...?之間的區別是什麼?「||」和「和「或」在Perl中?

似乎互聯網代碼使用它們兩個:

open (FILE, $file) or die("cannot open $file"); 
open (FILE, $file) || die("cannot open $file"); 
+9

請參閱`perldoc perlop`獲取優先級圖表,並參閱「邏輯或」部分以獲取更多示例:http://perldoc.perl.org/perlop.html#Operator-Precedence-and-Associativity – Telemachus 2009-07-16 10:31:17

+6

,使用詞法文件句柄和open的三參數形式。包含系統在參數中返回的錯誤:**`打開我的$ file_h,'<',$ file或者死亡「無法打開'$ file':$!」;`** – 2009-07-16 10:46:01

+1

或者「use autodie」 – jrockway 2009-07-16 20:28:12

回答

33

與Perl文件..

  • OR

這是列表操作符。在列表運算符的右側,它具有非常低的優先級,以便它控制在那裏找到的所有以逗號分隔的表達式。唯一具有較低優先級的運算符是邏輯運算符「和」,「或」和「不」,它們可用於評估對列表運算符的調用,而不需要額外的括號。 邏輯或,定義或獨家或

二進制「或」返回兩個周圍表達式的邏輯析取。這相當於||除非是非常低的優先級。這使得它對控制流程有用

print FH $data  or die "Can't write to FH: $!"; 

這意味着它短路:即只有在左表達式爲假時才評估右表達式。由於它的優先級,您應該避免將其用於分配,僅用於控制流。

$a = $b or $c;  # bug: this is wrong 
($a = $b) or $c;  # really means this 
$a = $b || $c;  # better written this way 

但是,當它是一個列表上下文分配,並且您嘗試使用「||」對於控制流,您可能需要「或」,以便分配具有更高的優先級。

@info = stat($file) || die;  # oops, scalar sense of stat! 
@info = stat($file) or die;  # better, now @info gets its due 

然後,您可以再次使用圓括號。

  • ||

如果任何列表操作者(印刷(),等等),或任何一元運算符(CHDIR(),等等)之後是一個左括號作爲下一個標記,括號內的操作者和參數取具有最高優先級,就像正常的函數調用一樣。例如,因爲命名一元運算符是比||更高的優先級:

chdir $foo || die; # (chdir $foo) || die 
chdir($foo) || die; # (chdir $foo) || die 
chdir ($foo) || die; # (chdir $foo) || die 
chdir +($foo) || die; # (chdir $foo) || die 
33

唯一的區別是他們的優先級。

open FILE, $file or die("cannot open $file"); # this works 
open FILE, $file || die("cannot open $file"); # this doesn't work 
open FILE, ($file || die("cannot open $file")); # why it doesn't work 
7

的 「& &」 和 「||」運營商優先於他們的「和」,「或」對等。

20

!&&||^具有高的優先級,使得它們在構建表達有用; not,and,orxor具有低優先級,使得它們對於實質上不同的表達式之間的流量控制是有用的。