Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask

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
[karlgoethebier]: this mad my day
[karlgoethebier]: no typo
[marioroy]: At the Fransiscan monastery, got stuck up high in a tree from pruning and the chainsaw with large branch fell and broke the latter, but not me fortunately. Was stuck there for a while until a firetruck came by.
[Corion]: marioroy: So you live dangerously ...
[Lady_Aleena]: s/latter/ladder/; # ? marioroy
[karlgoethebier]: marioroy: Praise the Lord
[marioroy]: Well, that's why there must be angels around, invisible or not.
[marioroy]: Lady_Aleena yes, ladder.
[marioroy]: Corion, no not intentionally. not at all.
[Lady_Aleena]: /ne tries to decide whther or not to take a hammer to hubby's alarm clock.

How do I use this? | Other CB clients
Other Users?
Others meditating upon the Monastery: (9)
As of 2017-05-29 08:36 GMT
Find Nodes?
    Voting Booth?