开发者

counting number of times items appear in an array..and order them

开发者 https://www.devze.com 2023-03-21 22:53 出处:网络
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);
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);

produces:

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

How can I order the output in descending order so that the most frequently-appearing is first? (The output does not necessarily have to be a hash):

$VAR1 = '2';
$开发者_JS百科VAR2 = 6;
$VAR3 = '3';
$VAR4 = 5;
$VAR5 = '4';
$VAR6 = 2;
$VAR7 = '1';
$VAR8 = 1;


Provide an appropriate function to sort:

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

精彩评论

暂无评论...
验证码 换一张
取 消