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

In reply to Substitute (s///) a set of times by jryan

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.