Saturday, July 9, 2011

How to create multi-dime​nsional array in perl?

You get a one-dimensional array because the array @a1 is expanded
inside the 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 multi-dimensional array, you have a few choices:

Direct assignment of each value
Dereferencing an existing array
Inserting a reference

The first option is basically $array[0][0] = 1; Not very exciting.

The second is doing this: my @a2 = (\@a1, 3); Note that this makes a
reference to the namespace for the array @a1, so if you later change
@a1, the values inside @a2 will also change. Not always a recommended
option.

A variation of the second option is doing this: my @a2 = ([1,2], 3);
The brackets will create an anonymous array, which has no namespace,
only a memory address, and will only exist inside @a2.

The third option, a bit more obscure, is doing this: my $a1 = [1,2];
my @a2 = ($a1, 3); It will do exactly the same thing as 2, only the
array reference is already in a scalar variable, called $a1.

Note the difference between () and [] when assigning to arrays.
Brackets [] create an anonymous array, which returns an array
reference as a scalar value (e.g. that can be held by $a1, or $a2[0]).

Parens on the other hand do nothing at all really, except change the
precedence of operators.

Consider this piece of code:

my @a2 = 1, 2, 3;
print "@a2";

This will print 1. If you use warnings, you will also get a warning
such as: Useless use of a constant in void context. What happens is
basically this:

my @a2 = 1;
2, 3;

Because commas (,) have a lower precedence than equalsign =. (See
"Operator Precedence and Associativity" in perldoc perlop)

What parens do is simply negate the default precedence of = and ,, and
group 1,2,3 together in a list, which is then passed to @a2.

So, in short, brackets [] have some magic in them: They create
anonymous arrays. Parens () just change precedence, much like in math.

There is much to read in the documentation. Someone here once showed
me a very good link for dereferencing, but I don't recall what it is.
In perldoc perlreftut you will find a basic tutorial on references.
And in perldoc perldsc you will find documentation on data structures
(thanks Oesor for reminding me).

No comments: