2
votes

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
persuant to the "arrow rule" perldoc perlreftut you don't need any of the -> in your example. This makes for cleaner looking multilevel hashes.Joel Berger
@JoelBerger: It's funny that you think removing -> makes the expression more readable. I have been known to introduce -> between components of a complex expression just for the same reason: to make it more readable. I guess readability is in the eye of the beholder :)Prakash K
@PrakashK, definitely eye of the beholder. My rule of thumb is usually: no arrows for purely data structures (especially of the same type, i.e. HoH or AoA, etc), always arrows for subroutine call/dereference and whatever is cleaner for anything else.Joel Berger

1 Answers

4
votes

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.