Sort hash keys of nested hash

2019-05-23 15:11发布

问题:

In perl, I have a hash that looks like the following:

   $hash{key1}->{a} = 1;
   $hash{key1}->{b} = 3;

   $hash{key2}->{a} = 4;
   $hash{key2}->{b} = 7;

   $hash{key3}->{a} = 2;
   $hash{key3}->{b} = 5;

How can I sort the keys of this hash by the value of key a. For instance, sorting the above hash in numerical ascending order by the values of key a would give: key1,key3,key2.

回答1:

perl has no notion of a sorted hash, you'll have to "sort" your keys in a foreach loop:

#!/usr/bin/perl -W
use strict;

my %hash = ();

$hash{key1}->{a} = 1;
$hash{key1}->{b} = 3;

$hash{key2}->{a} = 4;
$hash{key2}->{b} = 7;

$hash{key3}->{a} = 2;
$hash{key3}->{b} = 5;

print "$_\n" foreach sort {$hash{$a}->{a} <=> $hash{$b}->{a}} keys %hash;

Alternatively, you can put the result of the sort in an array and loop on this array.