通过内部哈希值对哈希散列进行排序

fug*_*ugu 0 sorting perl hash

我有哈希哈希

my %change;

while ( <DATA> ) {
    chomp;
    my ($gene, $condition, $change) = split;
    $change{$gene}{$condition} = $change;
}

print Dumper \%change;

__DATA__
gene1   condition1  10
gene2   condition1  0.5
gene3   condition1  1.5
gene1   condition2  2
gene2   condition2  13.5
gene3   condition2  0.25
Run Code Online (Sandbox Code Playgroud)

我想按价值排序:

gene2   condition2  13.5
gene1   condition1  10
gene1   condition2  2
gene3   condition1  1.5
gene2   condition1  0.5
gene3   condition2  0.25
Run Code Online (Sandbox Code Playgroud)

我正在使用:

for my $g (keys %change){
    for my $con (keys $change{$g}){
        for my $ch (sort { $change{$g}{$a} <=> $change{$g}{$b} } keys $change{$g}{$con} ) {
            print "$g\t$con\t$ch\n";
        }

    }
}
Run Code Online (Sandbox Code Playgroud)

但这不起作用,并产生错误

引用上的键的参数类型必须是untitled.pl第23行第6行的unblessed hashref或arrayref.

第23行是

for my $ch (sort { $change{$g}{$a} <=> $change{$g}{$b} } keys $change{$g}{$con}){
Run Code Online (Sandbox Code Playgroud)

谁能指出我正确的方向?

Bor*_*din 5

我认为你不太可能需要这样的哈希结构中的数据.当然,出于此任务的目的,您最好使用一组数组

use strict;
use warnings;

my @change;

while ( <DATA> ) {
    push @change, [ split ];
}

print "@$_\n" for sort { $b->[2] <=> $a->[2] } @change;


__DATA__
gene1   condition1  10
gene2   condition1  0.5
gene3   condition1  1.5
gene1   condition2  2
gene2   condition2  13.5
gene3   condition2  0.25
Run Code Online (Sandbox Code Playgroud)

产量

gene2 condition2 13.5
gene1 condition1 10
gene1 condition2 2
gene3 condition1 1.5
gene2 condition1 0.5
gene3 condition2 0.25
Run Code Online (Sandbox Code Playgroud)

如果您解释数据需要什么样的访问权限,那么我相信有更好的选择.例如,我建议%gene%condition哈希将基因或条件ID映射到使用该基因的数组元素列表.然后,当您知道基因或条件时,您可以访问数据

  • 这非常优雅 - 谢谢! (2认同)