[英]What is the difference between "||" and "or" in Perl?
C 風格的運算符&&
、 ||
之間有什么區別 , ... 以及他們的 Perl 人類可讀版本 " and
", " or
", ...?
似乎互聯網代碼同時使用了它們:
open (FILE, $file) or die("cannot open $file");
open (FILE, $file) || die("cannot open $file");
從Perl 文檔:
在列表運算符的右側,它具有非常低的優先級,因此它控制在那里找到的所有以逗號分隔的表達式。 唯一具有較低優先級的運算符是邏輯運算符“and”、“or”和“not”,它們可用於評估對列表運算符的調用,而無需額外的括號。
二進制“或”返回兩個周圍表達式的邏輯分離。 等價於
||
,除了非常低的優先級。 這使得它對控制流很有用
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
再說一次,你總是可以使用括號。
如果任何列表運算符(print() 等)或任何一元運算符(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
!
, &&
, ||
, 和^
具有高優先級,因此它們在構造表達式時很有用; not
、 and
、 or
和xor
具有低優先級,因此它們對於本質上不同的表達式之間的流控制很有用。
唯一的區別是它們的優先級。
open FILE, $file or die("cannot open $file"); # This works
open (FILE, $file) or die("cannot open $file"); # ...because it means this
open FILE, $file || die("cannot open $file"); # This doesn't work
open FILE, ($file || die("cannot open $file")); # ...because it means this
“&&”和“||” 運算符的優先級高於其對應的“and”、“or”。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.