为什么(至少)在perl 5.010中,//
的优先级低于==
?
例如这个
use 5.010;
my $may_be_undefined = 1;
my $is_equal_to_two = ($may_be_undefined//0 == 2);
say $is_equal_to_two;
(对我来说)打印出非常意外的结果。
最佳答案
这是因为//
以及==
属于运算符的类别。==
是“相等运算符”,尽管//
属于“C样式逻辑运算符”类别。
举个例子; &&
与//
处于同一“类别”中,当涉及到运算符优先级时,以下两个语句是等效的。这样可能更容易理解?
print "hello world" if $may_be_undefined && 0 == 2;
print "hello world" if $may_be_undefined // 0 == 2;
Documentation of C-style Logical Defined-Or ( // )
Although it has no direct equivalent in C, Perl's // operator is related to its C-style or. In fact, it's exactly the same as ||, except that it tests the left hand side's definedness instead of its truth.
Thus, $a // $b is similar to defined($a) || $b (except that it returns the value of $a rather than the value of defined($a)) and yields the same result as defined($a) ? $a : $b (except that the ternary-operator form can be used as a lvalue, while $a // $b cannot).
This is very useful for providing default values for variables. If you actually want to test if at least one of $a and $b is defined, use defined($a // $b) .
The ||, // and && operators return the last value evaluated (unlike C's || and &&, which return 0 or 1).
Documentation of Operator Precedence and Associativity
关于perl - 为什么//在perl中优先级比平等低?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8469273/