How can I tell if a set of parens in Perl code will act as grouping parens or form a list?

前端 未结 2 958
心在旅途
心在旅途 2021-01-12 09:21

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

2条回答
  •  不知归路
    2021-01-12 09:50

    1. Context.
    2. Parentheses don't have the role you think they have in creating a list.

    Examples:

    $x = 1 + 1;   # $x is 2.
    $x = (1 + 1); # $x is 2.
    @x = 1 + 1;   # @x is (2).
    @x = (1 + 1); # @x is (2).
    
    $x = (1 + 1, 1 + 2); # $x is 3.
    @x = (1 + 1, 1 + 2); # @x is (2, 3).
    

    Roughly speaking, in list context the comma operator separates items of a list; in scalar context the comma operator is the C "serial comma", which evaluates its left and right sides, and returns the value of the right side. In scalar context, parentheses group expressions to override the order of operations, and in list context, parentheses do... the exact same thing, really. The reason they're relevant in assigning to arrays is this:

    # Comma has precedence below assignment. 
    # @a is assigned (1), 2 and 3 are discarded.
    @a = 1, 2, 3; 
    
    # @a is (1, 2, 3).
    @a = (1, 2, 3);
    

    As for your question "is it a scalar or a one-element list", it's just not a meaningful question to ask of an expression in isolation, because of context. In list context, everything is a list; in scalar context, nothing is.

    Recommended reading: perlop, perldata, Programming Perl.

提交回复
热议问题