Beefy Boxes and Bandwidth Generously Provided by pair Networks
good chemistry is complicated,
and a little bit messy -LW
 
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
Re: frame shift in Perl string matching
by GrandFather (Cardinal) 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 meditating upon the Monastery: (7)
As of 2014-12-28 09:45 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    Is guessing a good strategy for surviving in the IT business?





    Results (180 votes), past polls