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 reference

With 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 error

and (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 array

which 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 12

And 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

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.