use strict; use warnings; my $s="foofoo"; my $ctr = 0; $s =~ s/(foo)/$ctr++?"bar":$1/ge; print "$s\n";