in reply to Perl assign scalar to array

Hello bagyi,

You’re right, it’s not working, but you don’t need to use strict to see that:

23:34 >perl -MData::Dump -wE "my @a = ('a'..'j'); @a[2..5] = 2; dd \@a +;" ["a", "b", 2, undef, undef, undef, "g" .. "j"] 23:35 >

(Assigning 2 here is equivalent to assigning a list with 2 as the only element. The missing elements default to undef.)

Slices are documented in perldata#Slices.

Hope that helps,

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

Replies are listed 'Best First'.
Re^2: Perl assign scalar to array
by ikegami (Patriarch) on Oct 14, 2015 at 19:32 UTC

    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.

      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,