in reply to What is a multidimensional array and how do I use one

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

Replies are listed 'Best First'.
Re: (dmm): What is a multidimensional array and how do I use one
by dmmiller2k (Chaplain) on Oct 31, 2001 at 00:16 UTC

    BTW, here's a little shortcut, using CGI.pm. Instead of this:

    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";

    Try this:

    # note that passing an array reference to Tr() creates a set of <TR> b +locks, one per element of the referenced array print table( Tr( [ map { td( $_ ) } @$db_results ] ) );

    Or, if you don't like the entire table stretched out into one long line of HTML, this:

    # need '*table' and '*Tr' in order to use start_table() and start_Tr() use CGI qw( :standard *table *Tr ); # ... # note the map() calls each represent a nested for() loop # and further that passing an array reference to td() creates a set of + <TD> blocks, one per element of the referenced array print join( "\n", start_table, start_Tr, (map { map { td($_) } @$_ } @$db_results), end_Tr, end_table ), "\n";

    Sorry ... couldn't help "improving" on your code :)

    dmm

    
    You can give a man a fish and feed him for a day ...
    Or, you can teach him to fish and feed him for a lifetime