0

Is there some perl "magic" to iterate through a hash sorted by the values but get the key in the iteration?

Sort by X and get X is easy (keys, values) - as well as sort by key and get the value.

Thanks!

chris01
  • 10,921
  • 9
  • 54
  • 93
  • 1
    No magic. You have to get all key-value pairs, sort them by value (yourself, using the appropriate function) and then take the key from each pair you are interested in. – Thilo Feb 10 '18 at 12:33
  • 1
    See also https://stackoverflow.com/questions/2886872/what-is-the-easiest-way-to-get-a-key-with-the-highest-value-from-a-hash-in-perl?rq=1 and https://stackoverflow.com/questions/7791958/sort-hash-by-value-and-key-in-that-order?rq=1 and https://stackoverflow.com/questions/5972224/the-simple-way-to-sort-based-on-values-in-a-hash-in-perl?rq=1 – Thilo Feb 10 '18 at 12:34
  • @Thilo: You don't have to *"get all key-value pairs"*: they're already sitting there, nicely paired-up, in the hash of data. – Borodin Feb 10 '18 at 14:24
  • @Borodin: I meant to say "you have to iterate over all the entries of the hash". No shortcut to that. – Thilo Feb 11 '18 at 10:42

2 Answers2

5
my %hash = ( one => 'a', two => 'b', three => 'c', four => 'd' );
for my $k ( sort { $hash{$a} cmp $hash{$b} } keys %hash ) {
    print "$k: $hash{$k}\n";
}
__END__
one: a
two: b
three: c
four: d
haukex
  • 2,973
  • 9
  • 21
3

Please remember in future to give an example of your data, the required result, and the code that you've written together with an account of what is wrong with it.

As it stands your question is very vague, and I have had to make several assumptions which may or may not be wrong

It isn't "magical"; you simply have to write the appropriate sort block

This will sort the keys of %hash in ascending lexical order of their corresponding values

my @sorted_keys = sort { $hash{$a} cmp $hash{$b} } keys %hash;

You may also make use of List::UtilsBy, like this. It may be significantly faster than the simple sort technique, depending on your data

use List::UtilsBy 'sort_by';

my @sorted_keys = sort_by { $hash{$_} } keys %hash;
Borodin
  • 126,100
  • 9
  • 70
  • 144