Here's a more general approach using 5.10's  \K assertion. The  {n} quantifier (where n could be $n) allows any occurrence to be replaced.

>perl -wMstrict -le "my $s = 'Foo|Fate|||Fate||||Pre|Fate|Post|||||Alive|Alive'; my $Fate = qr{ Fate }xms; my $not_Fate = qr{ (?! $Fate) . }xms; $s =~ s{ (?: $Fate $not_Fate*){2} \K $Fate }{}xms; print $s; " Foo|Fate|||Fate||||Pre||Post|||||Alive|Alive

Update: Here's a general approach based on split, but I doubt it will be significantly faster (if at all) than the regex approach. Works only for positive values of $n.

>perl -wMstrict -le "my $s = 'Foo|1ate|||2ate||||Pre|3ate|Post|||||4ate|Alive'; my $Fate = qr{ \d ate }xms; my $n = shift; my $x = 2 * $n; $s = join '', grep defined, (split /($Fate)/, $s, $n + 1)[0 .. $x - 2, $x] ; print qq{'$s'}; " 3 'Foo|1ate|||2ate||||Pre||Post|||||4ate|Alive'

In reply to Re^2: Replacing with null by AnomalousMonk
in thread Replacing with null by venkatperl55

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.