假设我有哈希数据结构的哈希结构如下:
%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
答案 0 :(得分:7)
你走在正确的轨道上。您可以在哈希中使用$a
和$b
内部变量,并以数字方式比较值(<=>
而不是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