排序数组散列:仅隔离最大的数组

时间:2018-08-16 20:30:05

标签: arrays perl sorting hash

我能够根据以下代码根据数组的大小对数组的哈希进行排序:

use strict; 
use warnings; 

my %HoA = (
flintstones    => [ "fred", "barney" ],
jetsons        => [ "george", "jane", "elroy" ],
simpsons       => [ "homer", "marge", "bart" ],
);

for my $key ( sort { @{$HoA{$b}} <=> @{$HoA{$a}} } keys %HoA ) {
    print "key: $key\tArray: @{$HoA{$key}} \n";
}

输出:

key: jetsons    Array: george jane elroy 
key: simpsons   Array: homer marge bart 
key: flintstones    Array: fred barney 

我想隔离所有因最大的阵列而进行的后续处理。在这种情况下,两个数组因最大而并列,每个数组的大小为3。我想要的输出看起来像:

key: jetsons    Array: george jane elroy 
key: simpsons   Array: homer marge bart

1 个答案:

答案 0 :(得分:3)

use strict;
use warnings;

use List::Util 'max';
use Data::Dump;

my %HoA = (
    flintstones => [ qw/ fred   barney / ],
    jetsons     => [ qw/ george jane  elroy / ],
    simpsons    => [ qw/ homer  marge bart / ],
);

my $max = max map { scalar @$_ } values %HoA;

dd [ grep { @$_ == $max } values %HoA ];

输出

[["george", "jane", "elroy"], ["homer", "marge", "bart"]]

或者完全匹配您所需的输出

while ( my ($k, $v) = each %HoA ) {
    next unless @$v == $max;
    printf "key: %-10s Array: %s\n", $k, "@$v";
}

输出

key: simpsons   Array: homer marge bart
key: jetsons    Array: george jane elroy