while (/(pattern)/g) { my $startpos = pos -= length $1; substr($_, $startpos, length $1, do_something($1)); pos = $startpos; }