As an additional insight into multidimensional arrays, consider the selectall_arrayref() method from DBI. It returns a reference to a list of references that are lists - or more sustinctly, a 2-Dimensional Array.

I use this method all the time at work, and dealing with 2-D arrays is a snap. The general rule is, for each dimension, you will need one for loop to iterate through the elements.

Let's say that you have just issued a database call and have the data stored in a reference. To make it easy, let's pretend that this bit of code is really that database call:

my $db_results = [ [qw(one two three)], [qw(four five six)], [qw(seven eight nine)], ];
$db_results is really a 2-Dimensional array, each list points to a list (or list of lists: LoL). Now, here is a cool way to use this data:
print "<table>\n"; foreach my $row (@$db_results) { print "\t<tr>\n"; foreach my $col (@$row) { print "\t\t<td>$col</td>\n"; } print "\t</tr>\n"; } print "</table>\n";
This yeilds a nice HTML table:
<table> <tr> <td>one</td> <td>two</td> <td>three</td> </tr> <tr> <td>four</td> <td>five</td> <td>six</td> </tr> <tr> <td>seven</td> <td>eight</td> <td>nine</td> </tr> </table>
As you can see, arrays and loops go hand in hand. Two array, two loops - three arrays, three loops. Four starts getting hairly, and five is right out! Sorry, MP joke. :)

jeffa


In reply to (jeffa) Re: What is a multidimensional array and how do I use one by jeffa
in thread What is a multidimensional array and how do I use one by Hopeless

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.