http://www.perlmonks.org?node_id=997918

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

Hi monks!

I'm using perl to analyze strings and need some suggestions on a seemingly easy problem.

What I want is to count occurrence of a keyword, $search, in my source string, $aa.

$aa="PPPP"; $search="PP"; $count =()= ($aa =~ /$search/g); print $count;

OUTPUT is 2, as the frame shifted 2 letters each step. But I want the frame to be shifting one letter each step, resulting in 3.

It seems there should be easier ways to achieve this, rather than using conditions and loops.

Thank you for your help and guidance.

Replies are listed 'Best First'.
Re: frame shift in Perl string matching
by GrandFather (Saint) on Oct 09, 2012 at 04:55 UTC

    Use a look ahead assertion:

    my $str = "PPPP"; my $search = "PP"; my $count = () = $str =~ /(?=$search)/g; print $count;
    True laziness is hard work

      Thanks!

Re: frame shift in Perl string matching
by AnomalousMonk (Archbishop) on Oct 09, 2012 at 07:12 UTC

    And if you want to capture the matches:

    >perl -wMstrict -le "my $s = 'PppP'; ;; my $search = qr{ (?i) pp }xms; my $count = my @captures = $s =~ m{ (?= ($search)) }xmsg; ;; print qq{found $count: (@captures)}; " found 3: (Pp pp pP)