Using Multi-Dimensional Arrays in Perl

Aug 22, 2002 - © Philip Yuson

A Perl array is a data type that allows you to store a list of items. You create them by assigning them to an array variable. The array variable is identified by an @ prefix.

To define a list of dates, make a one-dimensional array:

@array = ('20020701', '20020601', '20020501');


Two-Dimensional Arrays

Sometimes, you will want to have more than one dimension for your array. This is often the case for DBI database reads. In our example, we can add a title and author to each date.

We can create arrays for each date:

@array1 = ('20020701', 'Sending Mail in Perl', 'Philip Yuson');
@array2 = ('20020601', 'Manipulating Dates in Perl', 'Philip Yuson');
@array3 = ('20020501', 'GUI Application for CVS', 'Philip Yuson');

Since a list item is a scalar, we cannot put these into a list like this:

@main = (@array1, @array2, @array3);

The result would be similar to this:

@main = ('20020701', 'Sending Mail in Perl', 'Philip Yuson',
'20020601', 'Manipulating Dates in Perl', 'Philip Yuson',
'20020501', 'GUI Application for CVS', 'Philip Yuson');

From here, you can have a quasi-two dimensional table as long as you write a code to handle it that way. In Perl, you can simplify this. Instead of pumping these into one list, you can put the references of these arrays in the list:

@main = (\@array1, \@array2, \@array3);

Or to simplify:

@main = ( ['20020701', 'Sending Mail in Perl', 'Philip Yuson'],
['20020601', 'Manipulating Dates in Perl', 'Philip Yuson'],
['20020501', 'GUI Application for CVS', 'Philip Yuson']);

In this case, the @main list contains references to these arrays.

To reference the first column of the first row:

$ref = $main[0]; # set $ref to reference of @array1
$ref->[0]; # Returns the first item in @array

To simplify:

$main[0]->[0];

You can also simplify this as:

$main[0][0];

To get the value of the second column of the third row:

$ref = $main[2]; # Third row;
$ref->[1]; # second column;

Multi-Dimensional Arrays

To add more dimensional to your arrays, you can define array references:

@main = ( [ \@array1, \@array2, \@array3],
[ \@array4, \@array5, \@array6]);
The copyright of the article Using Multi-Dimensional Arrays in Perl in Perl is owned by Philip Yuson. Permission to republish Using Multi-Dimensional Arrays in Perl in print or online must be granted by the author in writing.


Articles in this Topic