Deepak Kumar Nayak Deepak Kumar Nayak - 6 months ago 15
Perl Question

count how many times a word occurs in a file and also in which lines?

let be explain In a text file "script.txt" i have to find "foo" word how many times of it Occurrence and in which lines and i have to list that lines.

Answer

Try as follow

my $total;
my $lines;
open my $fh,"<","file.txt";
while (<DATA>)
{
    if(my $ech_count = () = /\bfoo\b/g)
    {
        $total+=$ech_count;
        $lines.=$.."\n";
    }

}
print " Total count : $total\nLines are: \n $lines";

In above script $ech_count stores the number of matches in a lines it is perform by the = () =.

$. It is the perl inbuild special variable which give the current line number.