Search code examples
perlsortingcountkey

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 the following output?

A   456
C   344
B   234

Solution

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