OSA B17

 B17. Write a Perl program that reads a file and counts the number of lines, characters, and words it contains and also prints count of the number of times the word appeared

Program:

open(FILE, "<a.txt") or die "Could not open file: $!";
$lines=0;
$words=0;
$chars =0;
$same=0;
while (<FILE>) {
    $lines++;
    $chars += length($_);
    $words += scalar(split(/\s+/, $_));
}
print("lines=$lines words=$words chars=$chars\n");
open(FILE, "<a.txt") or die "Could not open file: $!";
while (<FILE>) {
    while (/(\w['\w]*)/g ) {
        $WORDS{$1}++;
    #{} denotes key
    #$WORDS{} stores key increment counter
    }
}


#foreach my $word ( sort { $WORDS{$b} <=> $WORDS{$a} } keys %WORDS) {
 #   printf "%5d %s\n", $WORDS{$word}, $word;
#}
foreach $word ( sort {  $WORDS{$b} <=> $WORDS{$b} } keys %WORDS  ) {
printf "%d %s\n",$WORDS{$word},$word
}

0 comments:

Post a Comment