我有一个哈希如下:
'4' => {
'25' => 'X',
'24' => 'Y',
'23' => 'Z'
},
'3' => {
'22' => 'S',
'15' => 'T'
},
'2' => {
'11' => 'A',
'21' => 'B',
'9' => 'C',
'17' => 'D',
'12' => 'E',
'20' => 'F',
'14' => 'G',
'4' => 'H',
'18' => 'I',
'19' => 'J',
'16' => 'K',
'10' => 'L',
'13' => 'M'
}
我想首先根据主键或2,3,4的第一个键进行排序。然后对于每个密钥,比如4,我想排序二级密钥,所以预期的输出将是:
'4' => {
'23' => 'Z',
'24' => 'Y',
'25' => 'X'
},
'3' => {
'15' => 'T',
'22' => 'S'
},
'2' => {
'4' => 'H',
'9' => 'C',
'10' => 'L',
'11' => 'A',
'12' => 'E',
'13' => 'M',
'14' => 'G',
'16' => 'K',
'17' => 'D',
'18' => 'I',
'19' => 'J',
'20' => 'F',
'21' => 'B'
}
我尝试了这段代码,但是二级密钥没有排序:
foreach $parentKey (sort {$a <=> $b} keys %orderedChoiceNameHash) {
for $childKey (sort {$orderedChoiceNameHash{$a} <=> $orderedChoiceNameHash{$b}} keys %{ $orderedChoiceNameHash{$parentKey}}) {
print $fh "$parentKey ::::: $childKey ::::: $orderedChoiceNameHash{$parentKey}{$childKey}\n";
}
}
答案 0 :(得分:2)
foreach my $key1 (sort {$b<=>$a} keys %hash)
{
foreach my $key2 (sort {$a<=>$b} keys %{ $hash{$key1} })
{
print "$key1\t$key2\t$hash{$key1}{$key2}\n";
}
}