An array of arrays is a two-dimensional structure that consists in an array whose elements are references to other arrays.
- Static initialization
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)
{
foreach $column (0..@{$filename[$row]})
{
print "Element [$row][$column] = $filename[$row][$column];
}
}





