Perl array vs list


I have two data structures in Perl:

An array:

my @array2 = ( "1", "2", "3");

for $elem (@array2) {
    print $elem."\n";

Giving me the following output:


And a list:

my @array = [ "1", "2", "3"];                                            

for $elem (@array) {
    print $elem."\n";

Giving the following output:


Obviously, I'd like to iterate over the elements in both cases, but why does the second solution give me only the reference to this array?


In Perl, arrays and lists are essentially the same thing, but your second example uses neither. Square brackets surround an array reference (a scalar value), and "assigning" a scalar to an array with something like my @array = $scalar is equivalent to my @array = ($scalar). Thus, the only element of @array in your second example is an array reference.

By : jwodder

This video can help you solving your question :)
By: admin