为什么//在 perl 中的优先级低于相等? [英] Why does // have lower precedence than equality in perl?
问题描述
为什么在(至少)perl 5.010 中 //
的优先级低于 ==
?
Why does //
have lower precedence than ==
in (at least) 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;
打印(对我而言)非常意外的结果.
prints (for me) very unexpected result.
推荐答案
这是因为 //
属于运算符的类别,以及 ==
.
It's because of the category of operators which //
falls under, aswell as ==
.
==
是等式运算符",尽管 //
属于C 风格的逻辑运算符".
==
is an "equality operator" though //
falls under the category of "C-style logical operators".
举个例子;&&
与 //
属于同一category",也就是说下面的两个语句在涉及到时是等效的运算符优先级.这样可能更容易理解?
As an example; &&
is in the same "category" as //
, with that said both of the statements below are equivalent when it comes to operator precedence. That might make it easier to understand?
print "hello world" if $may_be_undefined && 0 == 2;
print "hello world" if $may_be_undefined // 0 == 2;
<小时>
虽然它在 C 中没有直接的等价物,但 Perl 的//运算符与其 C 风格的 or 相关.实际上,它与 || 完全相同,只是它测试左侧的定义性而不是其真实性.
因此,$a//$b 类似于 defined($a) ||$b (除了它返回 $a 的值而不是 defined($a) 的值)并产生与 defined($a) 相同的结果?$a : $b (除了三元运算符形式可以用作左值,而 $a//$b 不能).
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).
这对于为变量提供默认值非常有用.如果您确实想测试是否至少定义了 $a 和 $b 之一,请使用 defined($a//$b) .
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) .
||、//和 &&运算符返回最后计算的值(与 C 的 || 和 && 不同,它们返回 0 或 1).
The ||, // and && operators return the last value evaluated (unlike C's || and &&, which return 0 or 1).
<小时>
这篇关于为什么//在 perl 中的优先级低于相等?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!