Question

Let's say I have a hash of hashes data structure constructed as followed:

%HoH => (
     flintstones => {
               family_members    => "fred;wilma;pebbles;dino",
               number_of_members => 4,
     },
     jetsons => {
               family_members    => "george;jane;elroy",
               number_of_members => 3,
     },
     simpsons => {
               family_members    => "homer;marge;bart;lisa;maggie",
               number_of_members => 5,
     },

)

How do I sort the keys, the families in this case, by the value number_of_members from greatest to least? Then I would like to print out the highest two. Here's a general idea but I know it's wrong:

foreach $value (
    sort {
    $HoH{$a}{$number_of_members} cmp $HoH{$b}{$number_of_members}
    } keys %HoH)
my $count = 0;
while ($key, $value) = each %HoH) {
    if (count <= 2){
        print "${HoH}{$key}\t$key{$value}";
    }
}
continue {
    $count++;
};

I want the code to print (the spaces are tab delimited):

simpsons    homer;marge;bart;lisa;maggie
flintstones    fred;wilma;pebbles;dino
Was it helpful?

Solution

You're on the right track. You use the $a and $b internal variables in the hash and compare the values numerically (<=> not cmp).

When printing, I find it easiest to store the keys in an array and use an array slice to access them.

use strict;
use warnings;

my %HoH = (
     flintstones => {
               family_members    => "fred;wilma;pebbles;dino",
               number_of_members => 4,
     },
     jetsons => {
               family_members    => "george;jane;elroy",
               number_of_members => 3,
     },
     simpsons => {
               family_members    => "homer;marge;bart;lisa;maggie",
               number_of_members => 5,
     },    
);
my @sorted = sort { $HoH{$b}{'number_of_members'} <=> 
                    $HoH{$a}{'number_of_members'} } keys %HoH;

for (@sorted[0,1]) {   # print only first two
    print join("\t", $_, $HoH{$_}{'family_members'}), "\n";
}

Output:

simpsons        homer;marge;bart;lisa;maggie
flintstones     fred;wilma;pebbles;dino
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top