http://www.perlmonks.org?node_id=388430

This subroutine will s/// a set number of times.

The obvious solution would seem to be: s/\Gpattern/blah/ while $count--, but that does not work because \G only works with m//, and s/(a)/<$1$1>/ while $count-- would restart the match each time at the beginning. (pos=0)

Usage is: subtimes($string, $number_of_times, $pattern, $string_to_substitute). You can include $dollar variables in $string_to_substitute, just make sure to remember to backslash the dollar variable in the string.

For instance, this: print subtimes("ababa", 2, qr/(a)/,"<\$1\$1>"); would print "<aa>b<aa>ba".

Update: Fixed a bug.

print subtimes($string, 2, qr/(a)/,"<\$1\$1>"); sub subtimes { my ($string, $count, $find, $tosub) = @_; no strict "refs"; my $newstring; while ($count--) { next unless $string =~ /($find)/; my ($num,%res) = 2; $res{$num++}=$$num while defined $$num; my ($matched, $startoffset, $endoffset, $temp) = ($1, $-[0], $ ++[0], $tosub); $temp =~ s/\$(\d+)/my $r=$1;$r++;$res{$r}/ge; $newstring .= substr($string, 0, $startoffset).$temp; substr($string, 0, $endoffset) = ''; } return $newstring.$string; }