OSA Group B: Perl program to read file and count lines, character and words

PDF Download

Source code:

#!/usr/bin/perl
while(1){
print "----------------------------";
print "\r\nPress 1 to read a file";
print "\r\nPress 2 to count number of lines";
print "\r\nPress 3 to count number of characters";
print "\r\nPress 4 to count number of words";
print "\r\nPress 5 to count occurence of a word";
print "\r\nPress 6 to exit: ";
print "\r\nEnter your choice: ";
$choice=<STDIN>;
if($choice == 6){
exit 0;
}
print "\r\nEnter the file to read: ";
$fname=<STDIN>;
print "\r\nFile name entered: $fname";
open FH, $fname or die "\r\nError opening file";
($lines, $words, $chars) = (0, 0, 0);
while (<FH>) {
$lines++;
$chars += length($_);
$words += scalar(split(/\s+/, $_));
}
if($choice == 1){
open FH, $fname or die "\r\nError opening file";
print "\r\nReading contents of file.\r\n";
while($line = <FH>){
print $line;
}
}
if($choice == 2){
print "Number of lines in file: $lines";
}
if($choice == 3){
print "Number of characters in file: $chars";
}
if($choice == 4){
print "Number of words in file: $words";
}
if($choice == 5){
print "\r\nEnter the word to count: ";
$word=<STDIN>;
chomp $word;
$wordC = 0;
$w = 0;
open FH, $fname or die "\r\nError opening file";
while (<FH>) {
$w = scalar(split(/$word/, $_));
if($w > 0){
$wordC += $w-1;
}
}
printf "\r\nThe word $word occurs $wordC times in file $fname";
}
close FH;
print "\r\n";
}
SHARE
    Blogger Comment
    Facebook Comment