in reply to replacing text you have already replaced...

You could save-and-restore pos:
while (/(pattern)/g) { my $startpos = pos -= length $1; substr($_, $startpos, length $1, do_something($1)); pos = $startpos; }
Basically open-coding the s///g operator with an extra last step to rescan what's already been seen.

-- Randal L. Schwartz, Perl hacker


update:

Whoa. Unnecessarily complicated there. This is simpler:

$_ = "aaa aaa aaa aaa"; while (/(aa)/g) { pos $_ -= length $1; substr($_, pos, length $1, "ba"); } print;
This prints "bba bba bba bba", because the "a" being replaced is allowed to match part of the next "aa" search, as expected.