我正在尝试根据数字键对嵌套哈希进行排序。在下面的代码中,$ keys(第一级)很容易排序,我试图找到一个关于排序我的哈希的$ position(第二级)的答案。请参阅下面的Data :: Dumper片段。 如果问题需要进一步澄清,请告诉我 感谢
my @array=();
foreach my $keys(sort({ $a <=> $b }keys %process)){
foreach my $position(sort({ $a <=> $b } keys %{$process{$keys}})){
foreach my $reference(keys %{$process{$keys}{$position}}){
my %min=();
my @arr1=();
while(my($allele,$frequency)=each %{$process{$keys}{$position}{$reference}}){
push(@arr1, "$keys\t$position\t$reference\t$allele\treference_val\t$frequency\n");
$min{1-$frequency}=1;
}
my $ref_min=(sort{$min{$b} <=> $min{$a}} keys %min)[0];
s/reference_val/$ref_min/g for @arr1;
push(@array,@arr1);
}
}
}
foreach(@array){
chomp;
print OUT $_,"\n";
}
数据::自卸车
$VAR1 = '1';
$VAR2 = {
'16977' => {
'G' => {
'A' => '0.0310014'
}
},
'77089' => {
'C' => {
'T' => '0.0171221'
}
},
'66442' => {
'T' => {
'A' => '0.0017295'
}
},
预期产出:
1 16977 G A 0.0310014
1 66442 C T 0.0171221
1 77089 T A 0.001
答案 0 :(得分:3)
在我看来,你 按排序顺序迭代第二级哈希。我运行你的代码(仅修改为STDOUT):
use strict;
use warnings;
my %process = (
'1' => {
'16977' => {
'G' => {
'A' => '0.0310014'
}
},
'77089' => {
'C' => {
'T' => '0.0171221'
}
},
'66442' => {
'T' => {
'A' => '0.0017295'
}
},
},
);
my @array=();
foreach my $keys(sort({ $a <=> $b }keys %process)){
foreach my $position(sort({ $a <=> $b } keys %{$process{$keys}})){
foreach my $reference(keys %{$process{$keys}{$position}}){
my %min=();
my @arr1=();
while(my($allele,$frequency)=each %{$process{$keys}{$position}{$reference}}){
push(@arr1, "$keys\t$position\t$reference\t$allele\treference_val\t$frequency\n");
$min{1-$frequency}=1;
}
my $ref_min=(sort{$min{$b} <=> $min{$a}} keys %min)[0];
s/reference_val/$ref_min/g for @arr1;
push(@array,@arr1);
}
}
}
foreach(@array){
chomp;
print STDOUT $_,"\n";
}
获得此输出:
1 16977 G A 0.9689986 0.0310014
1 66442 T A 0.9982705 0.0017295
1 77089 C T 0.9828779 0.0171221
与预期输出的不同之处在于它包含$ ref_min值,并且它在前两个之后具有不同顺序的列(因为它们是根据位置排序的)。你想以不同的方式行事?