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 |