in reply to Perl substitute with the nth match

Perhaps a programmatic pattern?

johngg@aleatico:~/perl/Monks$ perl -Mstrict -Mwarnings -E 'say q{}; my $text = <<__EOT__; cat dog cat mouse eel cat housecat catamaran fish __EOT__ my $n = 0; $text =~ s{cat(?{ $n++ })}{$n}g; say $text;' 1 dog 2 mouse eel 3 house4 5amaran fish

I hope this is helpful.

Cheers,

JohnGG

Replies are listed 'Best First'.
Re^2: Perl substitute with the nth match
by haukex (Archbishop) on Jan 12, 2023 at 18:47 UTC

    Just to add a note to this: while it may work in this case, in the general case, one should be careful with assuming how often a (?{...}) gets called, as is stated at the top of its documentation.