my $repl = 'xyz'; my $n = 2; my $i; $s =~ s/(sneak)/ ++$i == $n ? $repl : $1 /eg;