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

This faq says it isn't possible to impose an order on key-value pairs, which makes sense. However, is it possible to do some magic which returns an array of keys which are sorted by their hash values, or is this the same thing? If it isn't possible, is there a way to just return the endmost element of hash by sorted value? For instance, say I have a hash %scores = ('BlueTeam', 8, 'RedTeam', 2, 'GreenTeam', 4). Is it then possible to get back ('BlueTeam', 8), if I want the highest score? Granted, repeated values would complicate the issue; I'm assuming keys and values are unique.

Replies are listed 'Best First'.
Re: Quasi-sorting a hash by value
by btrott (Parson) on May 16, 2000 at 00:32 UTC
    Sure, you can do a sort by value, and keep the sorted list of keys in an array.
    my %hash = ( BlueTeam => 8, RedTeam => 2, GreenTeam => 4 ); my @sorted = sort { $hash{$b} <=> $hash{$a} } keys %hash; for my $team (@sorted) { print $team, " => ", $hash{$team}, "\n"; }
    Then, if you just want the largest one, that's in the 0th element of @sorted:
    printf "Largest is team %s: %d\n", $sorted[0], $hash{ $sorted[0] };
    Is that what you wanted?
Re: Quasi-sorting a hash by value
by ZZamboni (Curate) on May 16, 2000 at 00:43 UTC
    The answer to your question is in the same FAQ you cite. You cannot impose an order on how the keys are internally stored, or how they are returned by functions like keys or each. But you can certainly put the keys in an array in any order you want, like in the examples given in the faq or those given by btrott. You then use the array of sorted keys to access the array in the order you want.

    --ZZamboni

Re: Quasi-sorting a hash by value
by athomason (Curate) on May 16, 2000 at 00:40 UTC
    Heh, I feel a bit silly. Yes, this is what I wanted. That same code (essentially) was on the page I referenced ;-). I just assumed based on the comment above it that that code wasn't what I needed. Thanks.