Pages

Wednesday, August 7, 2013

Multi-Dimensional Arrays in Perl


Introduction to Arrays

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 a @ prefix. To define a list of dates, we do this:

@array = ('20020701', '20020601', '20020501');
This is a one-dimensional array.

Two-Dimensional Arrays

There will be times when 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 authors 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 so:


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

The result of this is 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. But in Perl, you can simplify this. Instead of pumping these into one list, you can put the references of these arrays to 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: We do this:

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

To make it simpler:
$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 dimensions to your arrays, you can define array references: 
@main = ( [ \@array1, \@array2, \@array3],
          [ \@array4, \@array5, \@array6]);

No comments:

Post a Comment