1

I'm having trouble with replacer strings that contain special characters with using s///:

> cat replace.pl
use strict;
use warnings;

my $orig_string = 'abc${abc}def';
my $replacer = '${abc}';
my $replacement = 'TEXT';
print "\nBefore replacement: $orig_string";
$orig_string =~ s/$replacer/$replacement/g;
print "\nAfter replacement: $orig_string";

print "\n";

exit;

Erroneous output:

> /usr/bin/perl replace.pl

Before replacement: abc${abc}def
After replacement: abc${abc}def

This works if I manually escape the $ in $replacer as my $replacer = '\${abc}';, but the replacer will have an unknown number and set of special characters in production.

Perl version:

> /usr/bin/perl -v

This is perl 5, version 16, subversion 3 (v5.16.3)
Elle Fie
  • 681
  • 6
  • 21
  • 1
    Consider a templating function like fill_in_string from [Text::Template](https://metacpan.org/pod/Text::Template) – Grinnz Feb 06 '20 at 20:44
  • `use strict; use warnings; use feature 'say'; my $str = 'abc${abc}def'; my $what = '\$\{abc\}'; my $to = 'TEXT'; say "Before: $str"; $str =~ s/$what/$to/; say "After: $str"; ` – Polar Bear Feb 06 '20 at 21:42

1 Answers1

2

You may use:

$orig_string =~ s/\Q$replacer\E/$replacement/g;

This will quote replacer string and will treat all special regex meta characters are literals.

Read more about quotemeta

You ma also use:

$replacer = quotemeta($replacer);

before substitution.

anubhava
  • 761,203
  • 64
  • 569
  • 643