Just looking through the archives to find a better solution than the one that I hacked up, but I couldn't find it!
So, I'll offer my CrapCode to the monestary or something
# FUNCTION: sub_with_str
# Safely do a pattern-matching substitution from two strings (i.e. the pattern
# itself and the substitution string - complete with $1's, etc - are passed in
# as strings. Note that no pattern validity check is done on $old_patt, check
# validity before calling this function. Return the new substituted string.
sub sub_with_str {
    my ($string, $old_patt, $new_patt) = @_;

    my @matches = ( $string =~ m/$old_patt/o );
    for (my $i=1; $i <= @matches; $i++) {
        # Find a dollar sign that is not preceeded by an escape character and
        # $i (a number). For example, $1foo${2}bar\$3 will match on $1 and
        # ${2}, but not on $3. Substitute all occurances with their actual
        # match, which was found above and put in the @matches array.
        my $patt_part = '';
        while ($new_patt =~ s/(.*?)(?:\A|(?<=[^\\]))\$(?:$i|\{$i\})(.*)/$2/) {
            $patt_part .= $1 . $matches[$i-1];
        }
        $new_patt = $patt_part . $new_patt;
    }

    # Get rid of any other $n (found as explained above) since they weren't
    # found as matches.
    $new_patt =~ s/(?:\A|(?<=[^\\]))\$(?:\d+|\{\d+\})//go;

    eval { $string =~ s/$old_patt/$new_patt/o };

    return $string;
}

In reply to Re: Handling scalars as regexs within a substitution. (Take 2) by Anonymous Monk
in thread Handling scalars as regexs within a substitution. (Take 2) by vroom

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.