在列表上下文中分配哈希有啥区别?
Posted
技术标签:
【中文标题】在列表上下文中分配哈希有啥区别?【英文标题】:What is a difference while assigning hash in list context?在列表上下文中分配哈希有什么区别? 【发布时间】:2021-03-10 09:37:00 【问题描述】:我要表达:
%MON = months => 1, end_of_month => 'limit'; # months => undef
%MON = ( months => 1, end_of_month => 'limit' );
为什么第一个表达式只有一个键 months
和 undef
值?
它们有什么区别?
【问题讨论】:
【参考方案1】:见perlop。 =
的优先级高于 =>
%MON = months => 1, end_of_month => 'limit';
相当于:
(%MON = "months"), 1, "end_of_month", "limit"
同时:
%MON = ( months => 1, end_of_month => 'limit' );
是:
%MON = ("months", 1, "end_of_month", "limit")
【讨论】:
【参考方案2】:这是 Perl 的运算符优先级表(来自 perlop):
left terms and list operators (leftward)
left ->
nonassoc ++ --
right **
right ! ~ \ and unary + and -
left =~ !~
left * / % x
left + - .
left << >>
nonassoc named unary operators
nonassoc < > <= >= lt gt le ge
nonassoc == != <=> eq ne cmp ~~
left &
left | ^
left &&
left || //
nonassoc .. ...
right ?:
right = += -= *= etc.
left , =>
nonassoc list operators (rightward)
right not
left and
left or xor
请注意,=
的优先级高于 ,
或 =>
。因此,您需要括号来覆盖优先级。
【讨论】:
=
在void
上下文中使用时的优先级应该更低吗?
@Eugen Konkov,在确定哪个运算符是哪个运算符的操作数之前,您无法确定运算符的上下文。解析必须在确定结果片段的上下文之前发生。例如,A = B && C; 1
中的 =
是在 void 上下文中求值的,但 A = B and C; 1
中的 =
是在标量上下文中求值的,你只知道这是因为优先级。 /// 还有一个问题是函数的最后一条语句和返回表达式的上下文直到运行时才知道,所以它不可能影响代码的编译方式。以上是关于在列表上下文中分配哈希有啥区别?的主要内容,如果未能解决你的问题,请参考以下文章