Tuesday, May 12, 2015

File the frequency of each word and print the output in the decreasing order

#!/usr/local/bin/perl

use strict;
use warnings;
my %count;
my $file = shift or die "Usage: $0 FILE\n";
open my $fh, '<', $file or die "Could not open '$file' $!";
while (my $line = <$fh>) {
        chomp $line;
        foreach my $str (split /\s+/, $line) {
             $count{$str}++;
        }
}

foreach my $str (reverse sort {$count{$a} <=> $count{$b}} keys %count) {
        printf "%-31s %s\n", $str, $count{$str};
}



USAGE: ./count.pl  txt1

OUTPUT:
are                               3
you                              3
Hii                               2
how                             2
hii                                2
i                                   1
Hoe                             1
am                               1
doing                           1
well                             1


No comments:

Post a Comment