Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer

frame shift in Perl string matching

by GTI (Initiate)
on Oct 09, 2012 at 04:18 UTC ( #997918=perlquestion: print w/replies, xml ) Need Help??
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 (Sage) 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


Re: frame shift in Perl string matching
by AnomalousMonk (Canon) 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)

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://997918]
Approved by GrandFather
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others wandering the Monastery: (5)
As of 2017-03-28 19:18 GMT
Find Nodes?
    Voting Booth?
    Should Pluto Get Its Planethood Back?

    Results (340 votes). Check out past polls.