Perl program to read file and count the occurrence of a string and print the number of occurrences.

Perl program to read a file content and search for a name in each line, count occurrence of the name (storing data in a hash) and print the statistics (line# and number of occurences)

—————————————————————————————–

—————————————————————————————–

use strict;
use warnings;

my $file = “1.txt”;
my $search_str = “kedar”;

&count_strings_in_file(file=>$file,str=>$search_str);

sub count_strings_in_file {
my %args = @_;
my $file = $args{file};
my $search_str = $args{str};

my $FH;
open ($FH, ‘<‘,$file) or die “Couldn’t open file: $!”;
my $count = 0;
my $line_no = 0;
my $hash = {};

while (<$FH>)
{
$line_no++;
if ($_ =~ /$search_str/i)
{
my @arr = split(” “,$_);
foreach my $word (@arr) {
if ($word eq $search_str) {
$count++;
}
}
}
$hash->{$line_no} = $count;
$count = 0;
}

foreach my $key (keys $hash) {
print “\nThis is line no.: ” . $key . ” and these many occurences: ” . $hash->{$key};
}

}

————————————————————————————————————-

————————————————————————————————————-

Advertisements

Tags: , ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s


%d bloggers like this: