in reply to Re: difference between \() and []
in thread difference between \() and []

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.

Replies are listed 'Best First'.
Re: Re: Re: difference between \() and []
by chromatic (Archbishop) on Mar 24, 2004 at 19:35 UTC

    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.

Re[3]: difference between \() and []
by Anonymous Monk on Mar 25, 2004 at 03:33 UTC

    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.