Saturday, 5 March 2016

Perl Program for Counting Number of Lines, Characters and Occurances of a Word

Q: Write a Perl Program to find the number of occurrences for a given word in a text file. Also display the number of characters, words and lines in the file.



Source Code

 
print "Enter the name of the file\n";
$inputf=(<>);
chomp($inputf);
$lines=0;
$char=0;
%words=0;

open(Data, "<$inputf");
while(<Data>)
{
print $_;
$lines+=1;
$char+=length($_);
chomp($_);
$words+=scalar(split(/\W+/,$_));
}

close Data;
print "Total no of lines : $lines\n"; 
print "Total no of characters : $char\n"; 
print "Total no of words : $words\n"; 

print "Enter the word whose number of occurrences you wish to  \n";
$w=(<>);
chomp($w);
$count =0;
$j=0;
open(Data, "<$inputf");

while(<Data>)
{
 $words+=scalar(split(/\W+/,$_));
 $str=$_;
 @arr=split(" ",$_);
 for($i=0;$i<$words;$i++)
 {
  if($w eq @arr[$i])
  {
  $count=$count+1;
  }
 }
}
print "The number of occurences for given word are :$count\n" ;


Output


[student@localhost grpb]$ perl perl.p
Enter the name of the file
file
The file contains multiple occurrences of words
word word word word
hello hello hi hi hi
test test check
end of file
Total no of lines : 5
Total no of characters : 116
Total no of words : 22
Enter the word whose number of occurrences you wish to
hi
The number of occurrences for given word are :3

No comments:

Post a Comment