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