Bob H has asked for the wisdom of the Perl Monks concerning the following question:

It's relatively basic, bu I've not been able to crack this from the quite repetitive help (same examples) that turn up everywhere based on perldoc.

Here's the code. Sorry if you'd have preferred without the html, but I thought it might make the job clearer - 'paste and go'.

Many thanks for any advice.
Bob H

------- #!/usr/bin/perl use CGI qw(:standard); print header; print start_html('hash of arrays'); print "<font size = +1><b>Sorting a hash of arrays by one of array ite +ms</b>\n"; print "<p>Add data with each data set in one array ...\n"; my %hoa = ( "array a" => [ "data a0", "data a1", "data a2", "data a3" ], "array b" => [ "data b0", "data b1", "data b2", "data b3" ], "array c" => [ "data c0", "data c1", "data c2", "data c3" ], ); print "<br>... done\n"; #------------------------- print "<p>Display data, without sorting ...\n"; print "<table border=1 bgcolor=AAAAFF>\n"; print "<tr><td bgcolor=FF99FF>hash</td><td bgcolor=FF99FF>data 0</td>< +td bgcolor=FF99FF>data 1</td><td bgcolor=FF99FF>data 2</td><td bgcolo +r=FF99FF>data 3</td></tr>\n"; for $data ( keys %hoa ) { print "<tr><td>$data:</td>\n"; for $i ( 0.. $#{ $hoa{$data} } ) { print "<td> $i = $hoa{$data}[$i] </td>"; } print "</tr>\n"; } print "</table>\n"; #------------------------- print "<p>Display data, sorted by 'hash' ...\n"; print "<table border=1 bgcolor=AAAAFF>\n"; print "<tr><td bgcolor=FF99FF>hash</td><td bgcolor=FF99FF>data 0</td>< +td bgcolor=FF99FF>data 1</td><td bgcolor=FF99FF>data 2</td><td bgcolo +r=FF99FF>data 3</td></tr>\n"; for $data ( sort ( keys %hoa ) ) { print "<tr><td>$data:</td>\n"; for $i ( 0.. $#{ $hoa{$data} } ) { print "<td> $i = $hoa{$data}[$i] </td>"; } print "</tr>\n"; } print "</table>\n"; #------------------------- print "<p>Display data, sorted by array 0 ...\n"; print "<p>help please!\n"; print "</font>\n"; print end_html; ------------

Replies are listed 'Best First'.
Re: ordering a hash of arrays by an array contents
by kyle (Abbot) on Oct 01, 2008 at 20:43 UTC
    sort { $hoa{$a}->[0] cmp $hoa{$b}->[0] } keys %hoa;

    Update: An expanded answer:

    my @sorted_keys = sort { $hoa{$a}->[0] cmp $hoa{$b}->[0] } keys %hoa; foreach my $row_key ( @sorted_keys ) { print "<tr><td>$row_key:</td>\n"; my $index = 0; foreach my $cell ( @{ $hoa{$row_key} } ) { print "<td>$index = $cell</td>"; $index++; } print "</tr>\n"; }

    This sorts the rows by the first element of the arrays within the rows.

      Monk Kyle, thanks very much indeed for your help. Really great!!! :) Bob