本文介绍了如何确定Perl代码中的一组parens是否将分组parens或形成列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在perl中,括号用于覆盖优先级(与大多数编程语言一样)以及用于创建列表.我怎么知道一对特定的括号将被视为分组构造还是一个单元素列表?

In perl, parentheses are used for overriding precedence (as in most programming languages) as well as for creating lists. How can I tell if a particular pair of parens will be treated as a grouping construct or a one-element list?

例如,我很确定这是一个标量,而不是一个元素列表:(1 + 1)
但是,更复杂的表达式呢?有一个简单的方法可以告诉吗?

For example, I'm pretty sure this is a scalar and not a one-element list: (1 + 1)
But what about more complex expressions? Is there an easy way to tell?

推荐答案

三个关键原则在这里很有用:

Three key principles are useful here:

上下文为王.对示例(1 + 1)的评估取决于上下文.

Context is king. The evaluation of your example (1 + 1) depends on the context.

$x = (1 + 1); # Scalar context. $x will equal 2. Parentheses do nothing here.
@y = (1 + 1); # List context. @y will contain one element: (2).
              # Parens do nothing (see below), aside from following 
              # syntax conventions.

在标量环境中,没有列表之类的东西.要查看此信息,请尝试将要显示的 列表作为标量变量.考虑这一点的方法是关注逗号运算符的行为:在标量上下文中,它评估其左自变量,将该值扔掉,然后评估其右自变量,然后返回该值.在列表上下文中,逗号运算符将两个参数都插入到列表中.

In a scalar context, there is no such thing as a list. To see this, try to assign what appears to be a list to a scalar variable. The way to think about this is to focus on the behavior of the comma operator: in scalar context it evaluates its left argument, throws that value away, then evaluates its right argument, and returns that value. In list context, the comma operator inserts both arguments into the list.

@arr  = (12, 34, 56); # Right side returns a list.

$x    = (12, 34, 56); # Right side returns 56. Also, we get warnings
                      # about 12 and 34 being used in void context.

$x = (@arr, 7);       # Right side returns 7. And we get a warning
                      # about using an array in a void context.

括号不会创建列表.逗号运算符创建列表(假设我们在列表上下文中).在Perl代码中键入列表时,出于优先考虑的原因需要括号,而不是出于创建列表的原因.一些例子:

Parentheses do not create lists. The comma operator creates the list (provided that we are in list context). When typing lists in Perl code, the parentheses are needed for precedence reasons -- not for list-creation reasons. A few examples:

  • 括号无效:我们正在按标量评估数组上下文,因此右侧将返回数组大小.

  • The parentheses have no effect: we are evaluating an array in scalarcontext, so the right side returns the array size.

$x = (@arr);

  • 创建具有一个元素的列表不需要括号.

  • Parentheses are not needed to create a list with one element.

    @arr = 33;         # Works fine, with @arr equal to (33).
    

  • 但是出于优先考虑,需要在多个项目中加上括号.

  • But parentheses are needed with multiple items -- for precedence reasons.

    @arr = 12, 34, 56; # @arr equals (12). And we get warnings about using
                       # 34 and 56 in void context.
    

  • 这篇关于如何确定Perl代码中的一组parens是否将分组parens或形成列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

    11-03 08:54