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; }