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

I've created a hash needed to roll out a table with HTML::Template. However I am currently sorting by keys which is not useful to me. I need to sort by field "$minie". Can anyone show me how to do this?
my $template = HTML::Template->new(filename => $temp_late, die_on_bad_params => 0); my @loop; # the loop data will be put in here # fill in the loop, sorted by timestamp foreach $count (sort keys %table) { # get the other data from the data hash ($eenie,$meenie,$minie,$mo,) = @{table{$count}}; # make a new row for this data - the keys are <TMPL_VAR> names # and the values are the values to fill in the template. my %row = ( eenie => $eenie, meenie => $meenie, minie => $minie, mo => $mo, ); # put this row into the loop by reference push(@loop, \%row); } # call param to fill in the loop with the loop data by referen +ce. $template->param(member => \@loop); # print the template print $template->output;

Replies are listed 'Best First'.
Re: sorting a hash for use in HTML:: Template
by valdez (Monsignor) on Jan 20, 2004 at 22:49 UTC

    perldoc -f sort
    for example:
    @by_minie = sort { $table{$b}->[2] <=> $table{$a}->[2] } keys %table;

    Ciao, Valerio

Re: sorting a hash for use in HTML:: Template
by Roger (Parson) on Jan 20, 2004 at 22:48 UTC
    You could extend the Schwartzian Transform a bit to get what you want. The foreach loop can be replaced by a one-liner:
    use strict; use warnings; use Data::Dumper; my %table = ( 'key1' => [ '1', 'Z', '2', '3' ], 'key2' => [ '1', 'A', '2', '3' ], ); print Dumper(\%table); my @loop = map { { eenie => $_->[0], meenie => $_->[1], minie => $_->[2], mo => $_->[3] } } sort { $a->[1] cmp $b->[1] } map { [@{$table{$_}}[0..3]] } keys %table; print Dumper(\@loop);

    And the output is as expected -
    $VAR1 = { 'key2' => [ '1', 'A', '2', '3' ], 'key1' => [ '1', 'Z', '2', '3' ] }; $VAR1 = [ { 'mo' => '3', 'eenie' => '1', 'minie' => '2', 'meenie' => 'A' }, { 'mo' => '3', 'eenie' => '1', 'minie' => '2', 'meenie' => 'Z' } ];