mobrule, Axeman and Sinan have all answered your question: you created a data structure 3 layers deep, instead of 2.
I am surprised that no one suggested using the core Data::Dumper library to help understand data structure questions.
use Data::Dumper;
my @a = [[1]];
print Dumper \@a;
This prints:
$VAR1 = [
[
[
1
]
]
];
Your error was using the array reference constructor []
instead of just using parenthesis (or nothing). @a = ([1]);
So, why does Perl have the weird []
and {}
syntax for declaring hash and array references?
It comes down to the fact that Perl flattens lists. This means that if you say: @a = (@b, @c);
that @a
is assigned the contents of @b
concatenated with the contents of @c
. This is is the same as Python's extend
list method. If you want @a
to have two elements, you need to force them not to expand. You do this by taking a reference to each array: @a = (\@b, \@c);
. This is like Python's append
list method.
When you want to create anonymous nested structures you need to have a way to mark them as hashes or arrays. That's where the syntax I mentioned above comes in.
But what good is list flattening? Why is it worth having this unusual syntax for making array and hash references, that is distinct from the syntax used for normal initialization?
List flattening means that you can easily assemble a list of subroutine parameters in a variable and then pass them in without doing anything tricky: foo(@some_args, 5, @more_args);
. See Apply on wikipedia for info on how this concept works in other languages. You can do all sorts of other nice things with map
and other functions.