sort hash by values *but* return keys

Viewed 42

The incoming file is in the form of account:data. In this case, the data are Y-SNPs.

I want to sort by value (SNPs) and return the key (account) with the data so that I can keep the two associated. This prints only the data. And doing a regular array sort on the second field doesn't work either.

#!/usr/bin/perl

@lines = <STDIN>;
chomp @lines;
foreach (@lines)
{
  (@f) = split /:/,$_;
  $h{$f[0]} = $f[1];
}

@s = map { [ $_, $h{$_} ] } sort values %h;
foreach (@s) {print "@$_\n"}
1 Answers

If you want to sort a hash by values but get the associated keys, you can do it with a custom sort function, i.e. something like this:

my @sorted_keys = sort { $h{$a} <=> $h{$b} } keys %h;

This will return the keys in %h in the order of their values, in this case sorted numerically with <=>. If you want to sort it alphabetically use cmp instead.

For more see the documentation of sort which even has a similar example:

# this sorts the %age hash by value instead of key
# using an in-line function
my @eldest = sort { $age{$b} <=> $age{$a} } keys %age; 
Related