in reply to Sort Values in Hash, While Tracking Keys.
A Schwartzian Transform may do the trick. You need to sort the values, which would be:
my @values = sort { $a <=> $b } values %hash;... but you need to keep track of the keys as well. You can build a temporary data structure of pairs, or a list of two-element array references, where the first element is the value and the second element is the key:
my @pairs = map { [ $hash{$_}, $_ ] } keys %hash;To get back the keys, you need to map over this list and extract the second element of each pair:
my @keys = map { $_->[1] } @pairs;That looks like a lot of useless work, and it would be, except that you can stick as many list-transforming functions in the middle as you want -- including a sort. You can also drop the temporary arrays; they're unnecessary. The result is:
my @keys_sorted_by_value = map { $_->[1] } sort { $a->[0] <=> $b->[0] } map { $hash{$_}, $_ } keys %hash;
Update: Fixed a typo found by Roy Johnson.
|
|---|