The simplest modification to your code as it stands would be using capturing parentheses (see Extracting matches and Backreferences in perlretut) to grab your tildes for your substitutions. I will also add the g modifer (see Modifiers in perlre) so you can replace all groups of tildes in one pass. Your code might then look like:

sub add_line_break { my (@out)=@_; for (@out) { s/(~+)/$1\n/g; } return wantarray ? @out :$out[0]; }

A logical change I would make (and a slight efficiency boost) would be to change that to a substitution applied to a location preceded by a tilde but not followed by a tilde:

s/(?<=~)(?!~)/\n/g;

That uses a positive look-behind and a negative look-ahead (see Looking ahead and looking behind in perlretut).

As a side note, when you want to understand what a regular expression does, check out YAPE::Regex::Explain. It can be very useful when learning regular expressions and when dealing with unfamiliar/old code.


In reply to Re: regex replacement help by kennethk
in thread regex replacement help by mkenney

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.