我真的需要一些帮助来理解这个哈希并用sort来处理它。
这是哈希:
$VAR1 = {
Key1:Key1_si => {
'KeyA' => {
Keya => 'abcd, defg',
keyb => '1000',
keyc => '80%',
keyd => '2011.10.09',
keye => '1234-UR-DDDD',
keyf => 'rwh',
keyg => '600',
keyh => 'red',
keyi => '900',
keyj => '',
keyk =>'int4678_tt',
},
'KeyB' => {
Keya => 'abcd, defg',
keyb => '2000',
keyc => '100%',
keyd => '2011.11.09',
keye => '1234-UR-DDDD',
keyf => 'rwh',
keyg => '500',
keyh => 'red',
keyi => '400',
keyj => '',
keyk =>'int4678_tt',
},
},
};
问题:我想根据值变化的'keyc'对此哈希进行排序。所以,我想在下面的基础上排序:
Key1:Key1_si->KeyB->Keyc
Key1:Key1_si->KeyA->keyc
另外,我希望输出带有排序值以及其他属性,如:
打印:
Key1:Key1_si KeyB Keya keyd Keyc keyf
Key1:Key1_si KeyA keya keyd Keyc keyf
有人可以帮我解决perl中的代码,以执行上面提到的排序。我将非常感谢您的时间和精力。
答案 0 :(得分:3)
您想要对密钥对列表进行排序,因此您必须首先构建密钥对列表。对数组的引用是明显的答案。一旦你弄清楚这一点,一切都是直截了当的。
建立密钥列表:
my @unsorted_keys;
for my $k1 (keys(%$VAR1)) {
for my $k2 (keys(%{ $VAR1->{$k1} })) {
push @unsorted_keys, [ $k1, $k2 ];
}
}
对这些键进行排序:
my @sorted_keys = sort {
my ($a_k1, $a_k2) = @$a;
my ($b_k1, $b_k2) = @$b;
( my $a_pc = $VAR1->{$a_k1}{$a_k2}{keyc} ) =~ s/%//;
( my $b_pc = $VAR1->{$b_k1}{$b_k2}{keyc} ) =~ s/%//;
$a_pc <=> $b_pc
} @unsorted_keys;
迭代排序的键:
for (@sorted_keys) {
my ($k1, $k2) = @$_;
my $hash = $VAR1->{$k1}{$k2};
... do stuff with %$hash ...
}