Using Multi-Dimensional Arrays in Perl


© 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]);

Go To Page: 1


The copyright of the article Using Multi-Dimensional Arrays in Perl in Perl is owned by . Permission to republish Using Multi-Dimensional Arrays in Perl in print or online must be granted by the author in writing.

Post this Article to facebook Add this Article to del.icio.us! Digg this Article furl this Article Add this Article to Reddit Add this Article to Technorati Add this Article to Newsvine Add this Article to Windows Live Add this Article to Yahoo Add this Article to StumbleUpon Add this Article to BlinkLists Add this Article to Spurl Add this Article to Google Add this Article to Ask Add this Article to Squidoo