$_ = "aaa aaa aaa aaa"; while (/(aa)/g) { pos $_ -= length $1; substr($_, pos, length $1, "ba"); } print;