user001
user001

Reputation: 1848

Sort hash keys of nested hash

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.

Upvotes: 2

Views: 2230

Answers (1)

fge
fge

Reputation: 121712

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.

Upvotes: 4

Related Questions