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

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,