I often want to do something like $a =~ s/$b/$c/g , where $b is a variable that may have regex metacharacters in it. Here's an example of the problem:
my $a = "$"; my $b = "$"; my $c = "x"; $a =~ s/$b/$c/g; print "a=$a\n";
This results in an error, because the string $b has a regex metacharacter, $, in it. Here's the alternative I've come up with so far:
# conceptually, the following is like $a=~s/$b/$c/, but is safe if $b +has metacharacters in it sub string_substitution_one { my $a_ref = shift; my $b = shift; my $c = shift; my $a = $$a_ref; my $debug = ($b eq '$m$'); my $i=index($a,$b); return 0 if $i == -1; my $z = ''; if ($i>0) {$z = $z . substr($a,0,$i)} $z = $z . $c; if ($i+length($b)<length($a)) {$z = $z . substr($a,$i+length($b),len +gth($a)-($i+length($b)))} $$a_ref = $z; return 1; } # conceptually, the following is like $a=~s/$b/$c/g, but is safe if $b + has metacharacters in it sub string_substitution_global { my $a_ref = shift; my $b = shift; my $c = shift; my $found = 0; while (string_substitution_one($a_ref,$b,$c)) { $found = 1; } return $found; }
Is there a simpler way to do this? I'm thinking of making this into a module, because I have several different programs that use it, but it seems like there must be an easier way to do such a common task. TIA!

In reply to s/$foo/$bar/ when $foo has metacharacters in it by bcrowell2

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.