Repeat after me:
Perl does not have multidimensional arrays
Perl does not have multidimensional arrays
Perl does not have multidimensional arrays
What Perl does have is have are arrays that contain references pointing to other arrays. You can emulate multidimensional arrays in Perl, but they are not true multidimensional arrays. For example:
my @array;
$array[0] = [ 1, 2, 3, 4, 5 ];
$array[1] = [ 1, 2, 3 ];
$array[2] = [ 1, 2 ];
I can talk about $array[0][1]
, and $array[2][1]
, but while $array[0][3]
exists, $array[2][3]
doesn't exist.
If you don't understand references, read the tutorial on references.
What you need to do is go through your array and then find out the size of each subarray and go through each of those. There's no guarantee that
- The reference contained in your primary array actually points to another array:
- That your sub-array contains only scalar data.
You can use the $#
operator to find the size of your array. For example $#array
is the number of items in your array. You an use ( 0..$#array )
to go through each item of your array, and this way, you have the index to play around with.
use strict;
use warnings;
my @array;
$array[0] = [ 1, 2, 3, 4, 5 ];
$array[1] = [ 1, 2, 3 ];
$array[2] = [ 1, 2, ];
#
# Here's my loop for the primary array.
#
for my $row ( 0..$#array ) {
printf "Row %3d: ", $row ;
#
# My assumption is that this is another array that contains nothing
# but scalar data...
#
my @columns = @{ $array[$row] }; # Dereferencing my array reference
for my $column ( @columns ) {
printf "%3d ", $column;
}
print "\n";
}
Note I did my @columns = @{ $array[$row] };
to convert my reference back into an array. This is an extra step. I could have simply done the dereferencing in my for
loop and saved a step.
This prints out:
Row 0: 1 2 3 4 5
Row 1: 1 2 3
Row 2: 1 2
I could put some safety checks in here. For example, I might want to verify the size of each row, and if one row doesn't match the other, complain:
my $row_size = $array[0];
for my $row ( 1..$#array ) {
my @columns = @{ $array[$row] };
if ( $#columns ne $array_size ) {
die qq(This is not a 2D array. Not all rows are equal);
}
}