$_ = 'foo' x 4; for(map { ++$i == 2 ? 'bar' : $_ } split(/(?=foo/, $_)) { $result .= $_; } print $result;