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