my $i; my $s =~ s/(sneak)/replace_third($1, ++$i)/eg; sub replace_third { my ($match, $i) = @_; if ($i == 3) {return "replacement string"} else {return "$match"} }