【问题标题】: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' );

为什么第一个表达式只有一个键 monthsundef 值? 它们有什么区别?

【问题讨论】:

    标签: perl operators operator-precedence assignment-operator perl-hash


    【解决方案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
      

      请注意,= 的优先级高于 ,=&gt;。因此,您需要括号来覆盖优先级。

      【讨论】:

      • =void 上下文中使用时的优先级应该更低吗?
      • @Eugen Konkov,在确定哪个运算符是哪个运算符的操作数之前,您无法确定运算符的上下文。解析必须在确定结果片段的上下文之前发生。例如,A = B &amp;&amp; C; 1 中的 = 是在 void 上下文中求值的,但 A = B and C; 1 中的 = 是在标量上下文中求值的,你只知道这是因为优先级。 /// 还有一个问题是函数的最后一条语句和返回表达式的上下文直到运行时才知道,所以它不可能影响代码的编译方式。
      猜你喜欢
      • 2016-03-20
      • 2012-04-03
      • 1970-01-01
      • 2012-09-12
      • 2023-03-04
      • 2011-08-31
      • 1970-01-01
      • 2016-07-31
      • 2020-08-17
      相关资源
      最近更新 更多