Progressive Matching
When used with the /g modifier, the
pos function allows you to read or
set the offset where the next progressive match will start:
$burglar = "Bilbo Baggins";
while ($burglar =~ /b/gi) {
printf "Found a B at %d\n", pos($burglar)–1;
}(We subtract one from the position because that was the length of
the string we were looking for, and pos is always the position just past the
match.)
The code above prints:
Found a B at 0 Found a B at 3 Found a B at 6
After a failure, the match position normally resets back to the
start. If you also apply the /c (for
“continue”) modifier, then when the /g runs out, the failed match doesn’t reset
the position pointer. This lets you continue your search past that point
without starting over at the very beginning.
$burglar = "Bilbo Baggins";
while ($burglar =~ /b/gci) { # ADD /c
printf "Found a B at %d\n", pos($burglar)–1;
}
while ($burglar =~ /i/gi) {
printf "Found an I at %d\n", pos($burglar)–1;
}Besides the three Bs it found
earlier, Perl now reports finding an i at position 10. Without the /c, the second loop’s match would have
restarted from the beginning and found another i at position 1 first.
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access