Quite right!!

I experimented with the g option, \G and pos() but they don't work with substitutions as they do with matches and in the end I couldn't find any RE based solution simpler than jwkrahn's that handles replacements that match the search pattern.

But I find REs difficult enought to understand without embeded code, so I came up with the following alternative which may have merit in some situations. It works for the examples you provided but it's not obvious that its doing replacement and the third argument to split is one more than the number of replacements, so it's certainly not ideal.

my $s1 = 'abaacaa'; my $s2 = 'abcdefg'; $s1 = join('aa', split('a', $s1, 4)); $s2 = join('aa', split(/[abcedfg]/, $s2, 4)); print "$s1\n"; print "$s2\n";

In reply to Re^4: Does Perl support a given number of replacements ? by ig
in thread Does Perl support a given number of replacements ? by Anonymous Monk

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.