Search code examples
perlhash-of-hashes

Sort both levels of keys for hash of hashes in perl


I have a code where I need to keep track of some values (that come up at random) at given positions in different categories (and a fairly large number of them; ~40,000), so I thought a hash of hashes would be the best way, with categories as first layer of keys, position as second and values as values; something like:

%HoH = {
      'cat1' => {
                  '7010' => 19,
                  '6490' => 13,
                  '11980' => 2
               }
      'cat2' => {
                  '7010' => 28,
                  '10470' => 13,
                  '205980' => 54
               }
        }

Then I need to sort and print them in order of both categories and then position, to get an output file like:

cat1    6490     13
cat1    7010     19
...
cat2    7010     28

But I can't work out the syntax for the nested sorting (alternatively, anyone got a better idea than this approach?)


Solution

  • Perl makes it easy to efficiently sort the keys while iterating through a hash of hashes:

    for my $cat (sort keys %HoH) {
        # numerical sort:
        for my $digits (sort { $a <=> $b } keys %{$HoH{$cat}}) {
            print join("\t", $cat, $digits, $HoH{$cat}{$digits}) . "\n";
        }
    }