You already got the answer to your question, don't use {}
, because that creates an anonymous hash reference.
However, there is still the matter of the question you didn't know you asked.
What is the difference between an array and a list in Perl?
In your question, you use the term 'list' as if it were interchangeable with the term array, but the terms are not interchangeable. It is important to understand the what the difference is.
An array is a type of variable. You can assign values to it. You can take references to it.
A list is an ordered group of zero or more scalars that is created when an expression is evaluated in a list context.
Say what?
Ok, conisder the case of my $foo = (1,2,3)
. Here $foo
is a scalar, and so the expression (1,2,3)
is evaluated in a scalar context.
On the surface it is easy to look at (1,2,3)
and say that's a literal list. But it is not.
It is a group of literal values strung together using the comma operator. In a scalar context, the comma operator returns the right hand value, so we really have ((1 ,2),3)
which becomes ((2),3)
and finally 3
.
Now my @foo = (1,2,3)
is very different. Assignment into an array occurs in a list context, so we evaluate (1,2,3)
in list context. Here the comma operator inserts both sides into the list. So we have ((1,2),3)
which evaluates to (list_of(1,2),3)
and then list_of(list_of(1,2),3)
, since Perl flattens lists, this becomes list_of(1,2,3)
. The resulting list is assigned into @foo
. Note that there is no list_of
operator in Perl, I am trying to differentiate between what is commonly thought of as a literal list and an actual list. Since there is no way to directly express an actual list in Perl, I had to make one up.
So, what does all this mean to someone who is just learning Perl? I'll boil it down to a couple of key points:
- Learn about and pay attention to context.
- Remember that your array variables are arrays and not lists.
- Don't worry too much if this stuff seems confusing.
- DWIM does, mostly--most of the time the right things will happen without worrying about the details.
While you are pondering issues of context, you might want to look at these links: