I can think of three reliable ways. The first is to replace everything after the Nth match with yourself.
my $max = 5; $s =~ s/(aa)/ $max-- > 0 ? 'bb' : $1 /eg;
It is not very effective if there are much more than N matches. To do this, we need to move the loop from the regex engine. The following two methods are ways to do this.
my $max = 5; my $out = ''; $out .= $1 . 'bb' while $max-- && $in =~ /\G(.*?)aa/gcs; $out .= $1 if $in =~ /\G(.*)/gcs;
And this time, in place:
my $max = 5; my $replace = 'bb'; while ($max-- && $s =~ s/\G.*?\Kaa/$replace/s) { pos($s) = $-[0] + length($replace); }
You may be tempted to do something like
my $max = 5; $s =~ s/aa/bb/ for 1..$max;
but this approach will not work for other patterns and / or replacement expressions.
my $max = 5; $s =~ s/aa/ba/ for 1..$max;
ikegami
source share