You get a one-dimensional array because the @a1 array expands inside parens. So, assuming:
my @a1 = (1,2); my @a2 = (@a1,3);
Then your second statement is equivalent to my @a2 = (1,2,3); .
When creating a multidimensional array, you have several options:
- Direct assignment of each value
- Selecting an existing array
- Link insertion
The first option is basically $array[0][0] = 1; Not very exciting.
The second does this: my @a2 = (\@a1, 3); Note that this makes a namespace reference for the @a1 array, so if you change @a1 later, the values ββinside @a2 will also change. Not always a recommended option.
A variant of the second option does the following: my @a2 = ([1,2], 3); The brackets will create an anonymous array that does not have a namespace, only a memory address and will exist only inside @a2 .
The third option, a little more obscure, does this: my $a1 = [1,2]; my @a2 = ($a1, 3); my $a1 = [1,2]; my @a2 = ($a1, 3); It will do the same as 2, only the array reference is already in the scalar variable called $a1 .
Note the difference between () and [] when assigning to arrays. The brackets [] create an anonymous array that returns a reference to the array as a scalar value (for example, which can be held by $a1 or $a2[0] ).
Parens, on the other hand, do nothing at all but change the priority of the statements.
Consider this piece of code:
my @a2 = 1, 2, 3; print "@a2";
1 open. If you use warnings , you will also receive a warning, for example: Useless use of a constant in void context . This mainly happens:
my @a2 = 1; 2, 3;
Because commas ( , ) have lower priority than equalsign = . (See "Operator Priority and Associativity" in perldoc perlop )
What parens does simply negates the default priority = and,, and group 1,2,3 together in the list, which is then passed to @a2 .
So, in short, the brackets [] have some magic in them: they create anonymous arrays. Parens () will simply change the priority, as in math.
You can read a lot in the documentation. Someone here once showed me a very good dereferencing link, but I donβt remember what it is. At perldoc perlreftut you will find a basic reference guide. And in perldoc perldsc you will find documentation on data structures (thanks to Oesor for reminding me).