Perl5 =(等于)运算符优先级
$a,$b,$c = 1,2,3;
print "$a, $b, $c\n";
那么
, , 1
= (等于) 是否比元组构造具有更高的优先级 - 这样做吗?
$a,$b,($c=1),2,3;
$a,$b,$c = 1,2,3;
print "$a, $b, $c\n";
returns
, , 1
So does = (equals) take higher precedence than the tuple construction - doing this?
$a,$b,($c=1),2,3;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
是的。 优先级表位于 perlop。赋值运算符为19级,逗号为20级。一般来说,Perl的运算符与相应的C运算符具有相同的优先级(对于那些具有相应C运算符的运算符)。
如果您的意思是
($a,$b,$c) = (1,2,3);
您必须使用括号。Yes. There's a precedence table in perlop. Assignment operators are level 19, and comma is level 20. In general, Perl's operators have the same precedence as the corresponding C operators (for those operators that have a corresponding C operator).
If you meant
($a,$b,$c) = (1,2,3);
you have to use the parens.您使用的逗号运算符(在标量上下文中)不适用于元组构造,它用于评估多个表达式并返回最后一个表达式。
Perl 根据上下文做不同的事情,它根据是否期望标量值、列表、什么都没有来决定做什么,...参见
perldoc perldata
关于Context 的介绍。因此,如果您这样做:
您将得到
0
,因为4,2,0
在标量上下文中计算,其行为类似于 C 的逗号运算符,计算逗号之间的表达式并返回最后一项的结果。如果您强制
4,2,0
在列表上下文中进行计算:您将得到
3
,因为分配给数组会强制列表上下文(附加括号用于解决提到的优先级问题 cjm),标量上下文中列表的值(通过成为标量上下文中and
的 RHS 强制)是它拥有的元素数量(逻辑and 返回最后一个表达式评估,而不是像其他编程语言中的布尔值)。
因此,正如 cjm 所说,您需要做的是:
处理优先级并强制列表上下文。
请注意两者之间的区别:
逗号运算符在标量上下文中计算,并返回 8。
逗号运算符在列表上下文中计算,并返回一个列表。
逗号运算符在列表上下文中计算,返回一个列表,然后对 $c 的赋值强制标量上下文,返回列表中的元素数量。
The comma operator as you used it (in scalar context) is not for tuple construction, it's for evaluating several expressions and returning the last one.
Perl does things differently depending on context, it decides what to do depending on if it's expecting a scalar value, a list, nothing at all, ... See
perldoc perldata
's section on Context for an introduction.So, if you do:
You get
0
, because4,2,0
is evaluated in scalar context, and behaves like C's comma operator, evaluating expressions between commas and returning the result of the last one.If you force
4,2,0
to be evaluated in list context:You get
3
, because assigning to an array forces list context (the additional parenthesis are there to solve the precedence issue cjm mentioned), and the value of a list in scalar context (forced by being the RHS of anand
in scalar context) is the number of elements it has (logicaland
in Perl returns the last expression evaluated, instead of a boolean value as in other programming languages).So, as cjm said, you need to do:
to deal with precedence and force list context.
Notice the difference between:
The comma operator is evaluated in scalar context, and returns 8.
The comma operator is evaluated in list context, and returns a list.
The comma operator is evaluated in list context, returning a list, then the assignment to
$c
forces scalar context, returning the number of elements in the list.