FYI, One possible way to do what you want is:

while (<DATA>) { next unless /^~/;# Skip line unless it starts with ~ tr/_/+/; } continue { print; }

The reason your /g version doesn't match is because /g doesn't try to match several times from the start of the string, but from the position last match. So after turning "~a_b_c_d" into "~a+b_c_d" it will start looking after the +, in the substring "b_c_d". Because this substring is not at the beginning of the string, ^ fails, (and ~ would obviously fail as well).

The \G anchor, meaning "from the last match" let's you express "and underscore after a ~ or any underscore after that":

pos($_) = -1; s/(^~ | \G) .*? \K _ /+/gx;
(^~|\G) can either match a ~ at the beginning of a string, or at the position of the last match. But since I have forced that position at -1, ^~ is the only possible alternative on the first try. Beyond that point, the s/// will run in a loop, where ^~ fails (because not at the beginning of the string), but \G matches the position of the last iteration.

NB: because $_ is the default variable, pos($_) = -1 can be simplified to pos = -1

NB2: and the reason jwkrahn's solution works is because instead of using /g, it calls the s/// operator in a loop, meaning it starts over again on each iteration (after turning "~a_b_c_d", it will run on "~a+b_c_d").


In reply to Re: /g option not making s// find all matches by Eily
in thread /g option not making s// find all matches by raygun

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.