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:
1
2
3
And a list:
my @array = [ "1", "2", "3"];
for $elem (@array) {
print $elem."\n";
}
Giving the following output:
ARRAY(0x9c90818)
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 tomy @array = ($scalar)
. Thus, the only element of@array
in your second example is an array reference.Lists in Perl are not data structures, they are positions in the source code, determined by the context around them. Lists are basically the transient structures that Perl uses to move data around. You interact with them with all of Perl's syntax, but you can not work with them as a data type. The data type that is closest to a list is an array.
When you write
[1, 2, 3]
what you are doing is creating a scalar array reference. That array reference is initialized with the list1, 2, 3
, and it is the same as creating a named array and taking a reference to it:Since the
[...]
construct creates a scalar, you should hold it in a scalar:Since you want to operate on the whole array, and not just the reference, you place a
@
in front of the$array
which dereferences the stored array reference.The square brackets are used to create an anonymous array. When evaluated, it returns a reference to this array, not the actual array values.
Parentheses have no such hidden property, but simply override precedence inside expressions, much like in math. For example:
Is actually evaluated like this:
because the
=
operator has higher precedence than the commas. So to get around that, we use parentheses when assigning arrays, like so:Your example:
is somewhat like saying this:
Where the
\
is used to create a reference to the@tmp
array.The square brackets create an anonymous array, populate the array with the contents of the brackets, and return a reference to that array. In other words,
is basically the same as
So the code should look like
or
If you want more clarification, see the the relevant documentation.
You could try and do some things for illustration purposes:
@array = ("1","2","3"); Here 1,2,3 is the element of @array variable. For ex. $array[0] is 1 , $array[1] is 2 and $array[2] is 3.
@array = ["1","2","3"]; Perl uses anonymous array references using [ ], so here basically only one element that you are storing, and that is the reference of an array ["1","2","3"] to the @array variable. for ex $array[0] is "ARRAY(0x9c90818)"
Hence while printing it is showing you the references.