Fellow Monks,
I am hoping you can help me better understand array references and the use of multi-dimensional arrays in Perl. I need to be able to iterate through the rows and columns of a two-dimensional array as well as add columns to existing rows.
My first attempt was to use an array reference when constructing the array:
my $table = [[1, 2, 3], [4, 5, 6]]; # using referenceWith this, I can iterate through all the elements:
for my $row (@{$table}) { for my $column (@{$row}) { print "$column\n"; } }
My two issues with this approach are that (1) I’m struggling with how to access an individual element of the table, such as the number 4
print "@{ $table }[1][0]\n"; # syntax errorand (2), how do I add additional elements so that $table ends up like this:
$table = [[1, 2, 3, 8], [4, 5, 6, 9]]I also tried the following:
my @table2 = [[7, 8, 9], [10, 11, 12]]; # using arraywhich allows me to do this to iterate through the values:
for my $row (@table2) { for my $column (@{$row}) { print "@{$column}\n"; for my $element (@{$column}) { print "$element\n"; } } }
As well as this to print individual elements:
print "@{$table2[0][1]}[2]\n"; # prints 12And add elements to the array:
push (@{$table2[0][1]}, 13); print "@{$table2[0][1]}\n"; # prints 10 11 12 13
But this method seems odd that I have to use 3 indices to access an element on a two-dimensional array.
Sorry for the long post but would appreciate some guidance on the best way to structure this array for idiomatic iteration and the ability to add elements after the array has been defined.
Gratias tibi ago
Leudwinus
In reply to Multi-Dimensional Arrays and Array References by Leudwinus
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |