<html>

Hi, while I was trying to convert some old sed programs which use the /n flag (substitute match n and nothing else) of the s/// operator to Perl, I was very disappointed when I discovered Perl does not support this flag. a2p/s2p do not either:


$ echo foofoofoofoo | sed 's/foo/bar/2'
foobarfoofoo
$ echo 's/foo/bar/2' | s2p
Unrecognized substitution command(2) at line 1
$ echo foofoofoofoo | awk '{print gensub(/foo/, "bar", 2)}'
foobarfoofoo
(as far as I know gensub() is only supported by GNU awk)
$ echo '{print gensub(/foo/, "bar", 2)}' | a2p
syntax error in file - at line 1
Translation aborted due to syntax errors

This code works:

@foos = split(/(?=foo)/, 'foo' x 4); $foos[1] = 'bar'; undef $_; for $elem(@foos) { $_ .= $elem; } print;
And this does too:
$_ = 'foo' x 4; for(map { ++$i == 2 ? 'bar' : $_ } split(/(?=foo/, $_)) { $result .= $_; } print $result;
but it's a bit too ugly for me, especially when used multiple times. Is the ability to substitute a specific match with a simple flag only found in the Land of Sed and Awk? I'm kind of suprised something as trivial as substituting an arbitrary match is simpler in sed and awk than Perl. Is there any reason selective substitution via flags was left out of Perl, or is this just an oversight? Or am I missing something obvious?

- A Shocked sed Addict


In reply to Selective substitution: not in Perl? 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.