Skip navigation.
Home
Your source for Perl tips, howto's, faq and tutorials
( categories: )

An array of arrays is a two-dimensional structure that consists in an array whose elements are references to other arrays.

- Static initialization

Each element of the array (let's call them subarrays) is also an array, so we use anonymous arrays to define each subarray:

Example:

@array_of_arrays =  ( [ "one", "two", "three" ],
                      [  4,   5,  6,  7  ],
                      [ "alpha", "beta" ]
                    );

To access the last element of the second array (number 6 in the example):

$element = $array_of_arrays[1][3];

- Dynamic initialization

There are many ways to initialize an array of arrays programatically. Below are a couple of them.

Examples:

Let's assume that you have a file called "filename.txt" and every line of this file consists of many words, each one separated by a comma and you want to store the contents of the file in an array of array structure:

open(FILENAME,"<filename.txt");
while ( <FILENAME> )
{
  chomp;
  push @filename, [ split /,/ ];
}

Another way to do it:

open(FILENAME,"<filename.txt");
$row = 0;
while ( <FILENAME> )
{
  chomp;
  @line = split /,/;
  foreach $column (@line)
  {
    push @{$filename[$row]}, $column;
  }
  $row++;
}

- Traversing an array of arrays

Example:

Assume we have an array of arrays named @filename

foreach $row (0..@filename-1)
{
  foreach $column (0..@{$filename[$row]})
  {
    print "Element [$row][$column] = $filename[$row][$column];
  }
}