Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine
 
PerlMonks  

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.

Comment on frame shift in Perl string matching
Download Code
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

      Thanks!

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

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://997918]
Approved by GrandFather
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others surveying the Monastery: (13)
As of 2015-07-28 20:06 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (258 votes), past polls