How can I sort a Perl hash on values and order the keys correspondingly (in two arrays maybe)?

Gogi picture Gogi · Jun 5, 2012 · Viewed 97.7k times · Source

In Perl, I want to sort the keys of a hash by value, numerically:

{
  five => 5
  ten => 10
  one => 1
  four => 4
}

producing two arrays:

(1,4,5,10) and (one, four, five, ten)

And then I want to normalize the values array such that the numbers are sequential:

(1,2,3,4)

How do I do this?

Answer

ikegami picture ikegami · Jun 5, 2012

First sort the keys by the associated value. Then get the values (e.g. by using a hash slice).

my @keys = sort { $h{$a} <=> $h{$b} } keys(%h);
my @vals = @h{@keys};

Or if you have a hash reference.

my @keys = sort { $h->{$a} <=> $h->{$b} } keys(%$h);
my @vals = @{$h}{@keys};