agynr has asked for the wisdom of the Perl Monks concerning the following question:

Hello Everybody, I want to search for a pattern like this '(a\s*bcd\s*e)(f\s*ghi)(jkl\s*tr) in a file. (The characters and the spaces can change in the pattern to be searched). I want to find the no. of occurences of the particular pattern in the file and if the pattern occurs once then I had to extract $1,$2,$3 and the pos of that found pattern. I am able to do like this
$pattern = (reement\s*PFPC\s*receives\s*fees\s*at\s*annual\s*rate\s*of +\s*)(#.{0,3}#)(\s*\s*of\s*average\s*net\s*asset\s*value\s*of\s*outsta +nding\s*In\s*) while ($data =~m/$pattern/gi) { $counter_number_of_search+=1; } if ($counter_number_of_search == 1) { ##### Do some operation ######## } else { ####### increase the margin to search ##### }
How can I find out the no. of occurences of the string in the data without going into the while loop. Please get a way out!!!!

Replies are listed 'Best First'.
Re: Searching no. of times the pattern occurs in the data
by prasadbabu (Prior) on Feb 12, 2005 at 05:22 UTC

    hi agynr, you can make use of undef $/;, and replace all the pattern using g.

    I have used $& which will take lots of memory and the process will be slow.To avoid that you can assign to another variable and replace with empty string instead of $&.

    undef $/; my ($count) = $data =~ s/((a\s*bcd\s*e)(f\s*ghi)(jkl\s*tr))/$&/gsi;

    Prasad

      If you put the pattern in a lookahead and replace with nothing, you'll save CPU cycles:
      my $count = s/(?=$pat)//gsi;

      If there are no capturing parentheses in the expression, you can simply use the match operator instead.

      my $count = () = /$pat/gsi;

      Caution: Contents may have been coded under pressure.