http://qs321.pair.com?node_id=761960


in reply to Re^2: foreach doesn't select array element
in thread foreach doesn't select array element

december:

I think you are also confused about Perl array and anonymous array syntax. The statement
    my @array = ('a', 'b', 'c');
constructs a list which is then used to initialize an array. The statement
    my $array_ref = ['a', 'b', 'c'];
constructs an anonymous array and returns a scalar reference to the array that is then used to initialize a scalar. See discussions of the  [ ] anonymous array constructor in perlref and perlreftut.

Consider the following examples:

>perl -wMstrict -MData::Dump=dump -le "my \@arr = [ 1, 2, 3, [ 'anna', 'beth', 'christie', 'denise' ], ]; dump @arr; " syntax error at -e line 1, near "my \" Global symbol "@arr" requires explicit package name at -e line 1. Global symbol "@arr" requires explicit package name at -e line 1. Execution of -e aborted due to compilation errors. >perl -wMstrict -MData::Dump=dump -le "my @arr; \@arr = [ 1, 2, 3, [ 'anna', 'beth', 'christie', 'denise' ], ]; dump @arr; " Can't modify reference constructor in scalar assignment ... near "];" Execution of -e aborted due to compilation errors. >perl -wMstrict -MData::Dump=dump -le "my @arr = [ 1, 2, 3, [ 'anna', 'beth', 'christie', 'denise' ], ]; dump @arr; print scalar @arr; " [1, 2, 3, ["anna", "beth", "christie", "denise"]] 1 >perl -wMstrict -MData::Dump=dump -le "my @arr = ( 1, 2, 3, [ 'anna', 'beth', 'christie', 'denise' ], ); dump @arr; print scalar @arr; " (1, 2, 3, ["anna", "beth", "christie", "denise"]) 4
Neither of the first two examples compile at all.

The third example initializes an array with a single element (as shown by the
    print scalar @arr;
statement), a scalar that is a reference to an anonymously constructed array.

The fourth example initializes an array with four elements (one of which happens to be a reference to yet another anonymous array).