简体   繁体   English

按键对Perl中的哈希数组排序

[英]Sort array of hashes in Perl by key

I define an array of hashes like this: 我定义了这样的哈希数组:

while (my $line = <PILEUP>) {
    if ($line =~ /INDEL/ and $line !~ /^#/) {
        chop $line;
        my @splitline = split(/\t/, $line);
        $hash2{$splitline[1]}{len} = length($splitline[4]);
        $hash2{$splitline[1]}{type} = "INDEL";
        push @{$hash1{$splitline[0]}}, %hash2;
    }
}

Then, I want to sort that array by the key of each hash: 然后,我想通过每个哈希的键对该数组进行排序:

for my $chr (keys %hash1) {
    my @sorted =  sort { $a->{ } <=> $b->{ } } @{%hash1{$chr}};
}

However, no clue how to continue here. 但是,不知道如何在这里继续。

I define an array of hashes like this: 我定义了这样的哈希数组:

No, you don't. 不,你没有。 You define a hash of arrays like that. 您可以像这样定义数组的哈希。

    chop $line;

chomp is preferable in just about every case. 几乎在每种情况下都最好是chomp During 10 years of programming Perl, I've only ever used chop as a curiosity. 在Perl编程的10年中,我只曾将chop用作好奇心。

    $hash2{$splitline[1]}{len} = length($splitline[4]);
    $hash2{$splitline[1]}{type} = "INDEL";
    push @{$hash1{$splitline[0]}}, %hash2;

Here, you push the keys and values of %hash2 onto the array inside %hash1 . 在这里,你推键和值%hash2到内部数组%hash1 You probably wanted to push the hash ref: \\%hash2 . 您可能想推送哈希引用: \\%hash2 But in that case you need to make it lexically scoped, or else it will push the same reference multiple times. 但是在这种情况下,您需要对其进行词法范围调整,否则它将多次推送相同的引用。

for my $chr (keys %hash1) {
    my @sorted =  sort { $a->{ } <=> $b->{ } } @{%hash1{$chr}};
}

This is in the right direction, except that you have to choose one (or more) of the hash values to sort by. 这是正确的方向,只是您必须选择一个(或多个)哈希值进行排序。 For example length and type. 例如长度和类型。 And you cannot use a loop. 而且您不能使用循环。

my @sorted_keys = sort { $hash1{$a}{len}  <=> $hash1{$b}{len} ||
                         $hash1{$a}{type} cmp $hash1{$b}{type} } keys %hash1;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM