1

假设我有一个哈希数据结构的哈希构造如下:

%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,
     },

)

我如何按number_of_members从最大到最小的值对键(在这种情况下为家庭)进行排序?然后我想打印出最高的两个。这是一个普遍的想法,但我知道这是错误的:

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++;
};

我想要打印代码(空格是制表符分隔的):

simpsons    homer;marge;bart;lisa;maggie
flintstones    fred;wilma;pebbles;dino
4

1 回答 1

7

你在正确的轨道上。您在哈希中使用$a$b内部变量并以数字方式比较值(<=>not cmp)。

打印时,我发现将键存储在数组中并使用数组切片来访问它们最容易。

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";
}

输出:

simpsons        homer;marge;bart;lisa;maggie
flintstones     fred;wilma;pebbles;dino
于 2013-02-18T19:18:45.717 回答