Tables

Sorry, there are no multi-dimentional tables in Perl. But you can use arrays of array references (or hashes or to other arrays to whatever depth)! These are done with references of course. Use a reference instead of a value and you get the gist.

my @table = ([1,2,3],[4,5,6],[7,8,9]);
 
foreach my $row (@table) {
  foreach my $col (@$row) {
    print $col;
  }
}
 
for (my $r=0; $r<=@#table; $r++) {
  for my ($c=0; $c<scalar $table[$r]; $c++) {
    print $table[$r]->[$c];
  }
}

But its better using all references! Really, its ends up being more consistent when you use all references. Having a master reference variable helps you mentally to code and understand the data structures.

my $table = [[1,2,3],[4,5,6],[7,8,9]];
 
foreach my $row (@$table) {
  foreach my $col (@$row) {
    print $col;
  }
}
 
for ($my $r=0; $r<scalar $table; $r++) {
  for ($my $r=0; $r<scalar $table->[$r]; $r++) {
    print $table->[$r][$c];
  }
}

Database Results

This is easily handled my building an array (row) of hashes (column names).

my $res = selectRows("select * from table");
## Format: $res->[row_number]{column_name}
 
foreach my $row ($res) {
  foreach my $colname (sort keys %$row) {
    print $row->{$colname};
  }
}
 
## Preferred... if you know your data as your should!
foreach my $row ($res) {
  foreach my $colname (qw( name address phone )) {
    print $row->{$colname};
  }
}
 
programming/perl/tables.txt · Last modified: 2005/07/18 17:14 by allen