Friday, October 15, 2010

Multi-dimensional Arrays in PERL

Since the advent of reference data type in PERL, it is now relatively easy to create multi-dimensional arrays.

Each element in an array must be scalar. Therefore, the following array is NOT an 2-D array, but actually is a 1-D array.

@onedarray = ((1,2,3),(4,5,6));
which is the same as @onedarray = (1,2,3,4,5,6);

Reference is actually a scalar that points to another data including an array. For example, $ref1 is a reference that points to an array. $ref2 is also a reference that points to another array.

$ref1 = [1,2,3];
$ref2 = [4,5,6];

Now to construct a 2-D array, we can use those two references as follows.

@twodarray = ($ref1,$ref2);

Or as a short cut, we could have used anonymous references. That is, we didn't need to explicitly declare the references before using them such as this.

@twodarray = ([1,2,3],[4,5,6]);

To read an element in the 2-D array, we use subscripts:

print $twodarray[0][0];

will print the content of the first element in the first array, which is 1.

print $twodarray[0][2];

will print the content of the third element in the first array, which is 3.

print $twodarray[1][2];

will print the content of the third element in the second array, which is 6.

We can explore further by creating 3-D array.

For example,

@threedarray = ([[1,2,3],[4,5,6]],[[7,8,9],[10,11,12]]);

print $threedarray[0][1][2];
will print 6.

No comments: