计算项目出现在数组中的次数......并对它们进行排序

时间:2011-07-21 22:41:29

标签: perl

my @array=qw(1 3 3 3 3 3 2 2 2 2 2 2 4 4);    
my %counts=();
map {$counts{$_}++} @array;
print Dumper(%counts);

产生

$VAR1 = '4';
$VAR2 = 2;
$VAR3 = '1';
$VAR4 = 1;
$VAR5 = '3';
$VAR6 = 5;
$VAR7 = '2';
$VAR8 = 6;

如何按降序排序输出,以便最常出现? (输出不一定必须是哈希):

$VAR1 = '2';
$VAR2 = 6;
$VAR3 = '3';
$VAR4 = 5;
$VAR5 = '4';
$VAR6 = 2;
$VAR7 = '1';
$VAR8 = 1;

1 个答案:

答案 0 :(得分:2)

sort提供适当的功能:

map {$counts{$_}++} @array;
foreach my $key (sort { $counts{$b} <=> $counts{$a} } keys %counts) {
    print "$key => count is $counts{$key}\n";
}