A simple perl program to count the occurences of a string in a given text.

In this program we are going to use the split function in perl to count the occurrences of a particular string in a given text.

#!/usr/bin/perl
#A perl program to count the occrrences of a particular string in a given text
print("Enter some text\n");
$text=" ".<stdin>." ";
print("Enter the string whose occurrences you want to count:");
$string=<stdin>;
chop($string);
@array= split(/$string/,$text);
$count=@array;
print("\nThe number of occurrences of the string \"$string\" is ". ($count-1)."\n");

Analysis

In line 5, if we don’t add the blank space before and after the text, we will not be able to count the occurrence of the string at the beginning and end.
In line 7 we are chopping the string to get rid of the new line character at the end, if we don’t do this we wont get the count we are expecting.
In line 8 we are using the split function. Split is a library function, it splits the string when ever it see the sub string between //.
for example @array=split(/the/, “this is a test string to, this string to split when ever there is an occurrence of the word this”);
now the array will have the following elements
$array[0]=” is a test string to, ”
$array[1]=”string to split when ever there is an occurrence of the word “

Tagged with 

One thought on “A simple perl program to count the occurences of a string in a given text.

  1. varun singh says:

    this one workd perfectly fine :)

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title="" rel=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>