in reply to Re: Perl assign scalar to array
in thread Perl assign scalar to array

Assigning 2 here is equivalent to assigning a list with 2 as the only element.

That's not right. It's not equivalent to assigning to a list; it is assigning a list. That should read "You are assigning a list consisting of 2 as its only element." I believe you think that @a=2 and @a=(2) are different, but they aren't. Parens don't create lists.

Replies are listed 'Best First'.
Re^3: Perl assign scalar to array
by Athanasius (Archbishop) on Oct 15, 2015 at 06:43 UTC

    Hello ikegami,

    I had to think carefully about this, but of course you’re right. Without parentheses:

    13:54 >perl -MData::Dump -wE "my @c = 2, 3; dd \@c;" Useless use of a constant (3) in void context at -e line 1. [2] 16:15 >

    the assignment occurs first, because the precedence of the assignment operator is higher than that of the comma operator. So the fact that assignment to an array puts the right-hand side into list context is irrelevent here. With scalar context imposed instead:

    16:35 >perl -wE "my $c = 2, 3; say $c;" Useless use of a constant (3) in void context at -e line 1. 2 16:36 >perl -wE "my $c = (2, 3); say $c;" Useless use of a constant (2) in void context at -e line 1. 3 16:36 >

    the parentheses act only to change the order of evaluation, because parenthesized expressions (“terms”1) have the highest precedence. So in a standard array assignment:

    16:36 >perl -MData::Dump -wE "my @c = (2, 3); dd \@c;" [2, 3] 16:36 >

    the assignment to an array puts the RHS into list context; the parentheses create a term; and within that term, the comma operator is “just the list argument separator, and inserts both its arguments into the list.”2 I think that makes sense. :-)

    Thanks for the clarification,

    1perlop#Terms-and-List-Operators-(Leftward).
    2perlop#Comma-Operator.

    Athanasius <°(((><contra mundum Iustus alius egestas vitae, eros Piratica,