Hash sort using the values

143 views Asked by At

I have a hash which is shown below. I want list of keys in sorted (ascending) order based on their values.

If the two different keys have same values, then it should print keys which is less first.

Let me show what's going wrong in my example:

#!/usr/bin/perl
use strict; use warnings;
use Data::Dumper;

my %hash = (
          '11' => 1,
          '315' => 4,
          '27' => 3,
          '60' => 4,
          '8' => 3,
          '4' => 2
);

my @keys = sort { $hash{$a} <=> $hash{$b} } keys(%hash);
print Dumper(\@keys);

Current Output:

$VAR1 = [
          '11',
          '4',
          '27',
          '8',
          '315',
          '60'
        ];

I want this to printed like below:

$VAR1 = [
          '11',
          '4',
          '8',
          '27',
          '60',
          '315'
        ];

Since 60's value is 4 and 315's value is also 4. I want 60 to be printed first and 315 later since 60 is lesser than 315 (I mean based on the key's value). Just assuming this can be done using Tie::SortHash (not sure)?

2

There are 2 answers

0
toolic On BEST ANSWER

Change the sort to sort numerically on values, then on keys:

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

Output:

$VAR1 = [
          '11',
          '4',
          8,
          27,
          60,
          315
        ];

Refer to perlfaq4: How do I sort a hash (optionally by value instead of key)?

From your command line, you can look up common questions with a command like:

perldoc -q sort
0
ikegami On
use Sort::Key::Multi qw( uukeysort );

my @keys =
   uukeysort { $hash{ $_ }, $_ }
      keys( %hash );