in reply to difference between \() and []

At the risk of starting a huge, subtle argument, () does not create a list. (I can throw around the terms lvalue, rvalue, and context if you like, but I think you'll do better if you just keep my first sentence in mind.)

Replies are listed 'Best First'.
Re: Re: difference between \() and []
by eXile (Priest) on Mar 24, 2004 at 19:08 UTC
    Please do start the huge, subtle argument. 8)

    Is it that, in this rvalue-case, () makes its content evaluated in list context instead of creating a list? In that case I think I'm starting to get it.

      I'd say that parenthesis only group things on the right hand side of an expression. They can enforce list context on the left hand side of an expression, especially if it'd normally be a scalar expression.

        Checking my intuition/understanding here:

        @a = (1, 2, 3); # works as expected @a = 1, 2, 3; # Equivalent to (@a = 1), 2, 3;

        The assignment operator (equals) binds tighter than the comma operator, so in the second case, the assignment is done, then the rest of the commas are processsed. Thus

        $d = ( @a = 1, 2, 3 ); print "$d\n"; print "@a\n";

        prints "3" and "1". $d gets the last value in the comma list, which is being evaluated in scalar context because of the scalar assignment.

        Thus in the first example, () doesn't create a list, it just changes the precedence so that all the comma operators evaluate together (and in list context because of the context of the assignment, thus returning a list).

        Wow. Never really thought about that before. Thanks, chromatic. I'm not entirely sure why parentheses create list context for lvalues, but I guess that's further homework and grepping through perldoc.

        -xdg

        Code posted by xdg on PerlMonks is public domain. It has no warranties, express or implied. Posted code may not have been tested. Use at your own risk.

      The only way I can keep my sanity in this regard is to repeat the following mantra: there is no such thing as a list in scalar context.

      An array in scalar context returns its length. A hash returns its number of buckets. The comma operator returns its right operand, as in  my $foo = (1,2,3); A subroutine returns whatever it wants to. Every Perl construct or operator that can be used in an expression does well defined, but sometimes different, things in scalar or list context. See List is a Four-Letter Word.