”、“或”、...? 似乎互联网代码同时使用了它们: open (FILE, $file) or die("c-6ren">
gpt4 book ai didi

perl - Perl 中的 "||"和 "or"有什么区别?

转载 作者:行者123 更新时间:2023-12-03 07:35:46 27 4
gpt4 key购买 nike

C 风格运算符 &&||、... 与其 Perl 人类可读版本“and”之间有什么区别>”、“”、...?

似乎互联网代码同时使用了它们:

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

最佳答案

来自Perl documentation :

列出运算符

On the right side of a list operator, it has very low precedence, such that it controls all comma-separated expressions found there. The only operators with lower precedence are the logical operators "and", "or", and "not", which may be used to evaluate calls to list operators without the need for extra parentheses.

逻辑、定义以及互斥

Binary "or" returns the logical disjunction of the two surrounding expressions. It's equivalent to ||, except for the very low precedence. This makes it useful for control flow

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

This means that it short-circuits: i.e., the right expression is evaluated only if the left expression is false. Due to its precedence, you should probably avoid using this for assignment, only for control flow.

$a = $b or $c; # Bug: this is wrong
($a = $b) or $c; # Really means this
$a = $b || $c; # Better written this way

However, when it's a list-context assignment and you're trying to use "||" for control flow, you probably need "or" so that the assignment takes higher precedence.

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

Then again, you could always use parentheses.

||

If any list operator (print(), etc.) or any unary operator (chdir(), etc.) is followed by a left parenthesis as the next token, the operator and arguments within parentheses are taken to be of highest precedence, just like a normal function call.

<小时/>

For example, because named unary operators have higher precedence than ||:

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

关于perl - Perl 中的 "||"和 "or"有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1136583/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com