Here's a quick little subroutine that I wrote awhile back that I use a fair amount. It will sort a multidimensional hash by the value of whatever "column" you specify and throw the sorted keys back to you.

BTW, I sometimes use this more than once in a script to filter results down...that is why I pass an array ref as the last arg (so I can filter if need be).

Was able to remove the temp hash based on what Juerd wrote...Could have sworn I tried formatting the compare that way.

$hash{'1'}->{"person"} = "Me"; $hash{'1'}->{"age"} = "27"; $hash{'2'}->{"person"} = "Wife"; $hash{'2'}->{"age"} = "26"; $hash{'3'}->{"person"} = "Dad"; $hash{'3'}->{"age"} = "54"; $hash{'4'}->{"person"} = "Brother"; $hash{'4'}->{"age"} = "24"; my @sortedKeys = sortHashByColumn(\%hash,"age","desc",[keys %hash]); foreach my $sortedKey(@sortedKeys){ print "$sortedKey: " . $hash{$sortedKey}->{'age'} . " " . $hash{$s +ortedKey}->{'person'} . "\n"; } sub sortHashByColumn{ my($hashRef,$sortColumn,$sortDirection,$keysAR) = @_; my @sortedKeys; my $sortType; # VERIFY THAT THIS IS A VALID COLUMN if(! defined $hashRef->{$$keysAR[0]}->{$sortColumn}){ print "sortHashByColumn Error: $sortColumn is not a column in +this hash.\n"; exit(0); # VALID COLUMN, FIGURE OUT IF IT IS A NUMERIC COLUMN OR ALPHA } else { if($hashRef->{$$keysAR[0]}->{$sortColumn} =~ /^\d+/){ $sortType = "numeric"; } else { $sortType = "alpha"; } } if($sortType eq "numeric"){ if($sortDirection =~ /asc/i){ @sortedKeys = sort { $hashRef->{$a}{$sortColumn} <=> $hash +Ref->{$b}{$sortColumn} } @$keysAR; } else { @sortedKeys = sort { $hashRef->{$b}{$sortColumn} <=> $hash +Ref->{$a}{$sortColumn} } @$keysAR; } } else { if($sortDirection =~ /asc/i){ @sortedKeys = sort { $hashRef->{$a}{$sortColumn} cmp $hash +Ref->{$b}{$sortColumn} } @$keysAR; } else { @sortedKeys = sort { $hashRef->{$b}{$sortColumn} cmp $hash +Ref->{$a}{$sortColumn} } @$keysAR; } } return @sortedKeys; }

Replies are listed 'Best First'.
Re: Sort Multidimensional Hash By Column
by Juerd (Abbot) on Dec 20, 2001 at 03:08 UTC
    I'd never create a sub for that.
    %h = ( pizza => { foo => 14, bar => 29 }, shoarma => { foo => 2, bar => 53 }, gyros => { foo => 10, bar => 35 }, ); @keys_sorted_foo_ascn = sort { $h{$a}{foo} <=> $h{$b}{foo} } keys %h; @keys_sorted_foo_desc = sort { $h{$b}{foo} <=> $h{$a}{foo} } keys %h; @keys_sorted_bar_ascn = sort { $h{$a}{bar} <=> $h{$b}{bar} } keys %h; @keys_sorted_bar_desc = sort { $h{$b}{bar} <=> $h{$a}{bar} } keys %h;

    I find this a LOT easier than using a sub.

    2;0 juerd@ouranos:~$ perl -e'undef christmas' Segmentation fault 2;139 juerd@ouranos:~$