You're on the right track. The global matching starts at the position where the last match ended. You can use \G to mark the position, but you can't move it backwards. For overlapping matches, you need look around assertions:
my $string = '123perl456perl789perl10';
while ($string =~ /(?<=(..))perl(?=(..))/g) {
print "$1perl$2\n";
}
Where (?<=...) means "is immediately preceded by", and (?=..) stands for "is immediately followed by". The look around assertions are not part of capturing (that's why you need to add capturing parentheses into the assertions), and they don't affect the position of the match.
($q=q:Sq=~/;[c](.)(.)/;chr(-||-|5+lengthSq)`"S|oS2"`map{chr |+ord
}map{substrSq`S_+|`|}3E|-|`7**2-3:)=~y+S|`+$1,++print+eval$q,q,a,
| [reply] [d/l] [select] |
This is what I think of as the standard approach to this sort of problem: it's my reflexive First Thought whenever I hear or read "overlapping match":
c:\@Work\Perl>perl -wMstrict -le
"my $s = '123perl456perl789perl10';
;;
my @caps = $s =~ m{ (?= (.. perl ..)) }xmsg;
;;
print qq{'$_'} for @caps;
"
'23perl45'
'56perl78'
'89perl10'
It has the advantages of using only a single capture group, and of needing no look-behind, which has the limitation in Perl regex of being fixed width.
Update: Please see perlre, perlretut (especially Looking ahead and looking behind), and perlrequick.
Give a man a fish: <%-{-{-{-<
| [reply] [d/l] [select] |
Normally, regex matches don't overlap. Here's one article that explains how to solve it with a lookahead assertion: http://linuxshellaccount.blogspot.com/2008/09/finding-overlapping-matches-using-perls.html
my $string = "123perl456perl789perl10";
while ($string=~m/(.{2}perl(?=(.{2})))/gp)
{ print "$1$2\n" }
| [reply] [d/l] |
(Dont know why my posts lose all formatting and paragraphs though)
That's because you haven't put any formatting into your posts! PerlMonks posts are HTML formatted by the poster (or by a janitor if you've been really naughty). Please see Writeup Formatting Tips and at the very least use <p> ... </p> (paragraph) tags for text and <c> ... </c> (code) tags for code/data/input/output.
Give a man a fish: <%-{-{-{-<
| [reply] [d/l] [select] |