in reply to regex replacement help

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.

Replies are listed 'Best First'.
Re^2: regex replacement help
by Eliya (Vicar) on Mar 29, 2011 at 19:22 UTC
        s/(~+)/$1\n/g;

    Another variant would be to use the (relatively new) \K ("Keep the stuff left of the \K"), which avoids having to capture/re-insert the matched fragment:

    s/~+\K/\n/g;
Re^2: regex replacement help
by mkenney (Beadle) on Mar 29, 2011 at 19:09 UTC
    Thanks for all the info! I'm going to pull up those articles tonight!!!