Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Perl, how do I sort by frequency of a value?

I am trying to create a program to count the different values that occur in a column of a data file. So, it would be something like, if the possible values of a column are A, B, C. The output is something like

A   456
B   234
C   344

I have been able to get the running counts of A, B and C easily by doing something like this

my %count; 
for my $f (@ffile) {

    open F, $f || die "Cannot open $f: $!";

    while (<F>) {
       chomp;
       my @U = split / /;

       $count{$U[2]}++; 
    }

}
   foreach my $w (sort keys %count) {
         printf $w\t$count{$w};
     }

For instance here I am counting the second column of the file in the path given.

How do I sort the output of the printf by the counts rather than the keys (or values A, B, C) to get -

A   456
C   344
B   234
like image 279
sfactor Avatar asked Dec 23 '10 15:12

sfactor


1 Answers

This is a FAQ:

perldoc -q sort

use warnings;
use strict;

my %count = (
    A => 456,
    B => 234,
    C => 344
);

for my $w (sort { $count{$b} <=> $count{$a} } keys %count) {
    print "$w\t$count{$w}\n";
}

__END__
A       456
C       344
B       234
like image 146
toolic Avatar answered Oct 13 '22 06:10

toolic