I'm trying to escape several special characters in a given string using perl regex. It works fine for all characters except for the dollar sign. I tried the following:
my %special_characters;
$special_characters{"_"} = "\\_";
$special_characters{"$"} = "\\$";
$special_characters{"{"} = "\\{";
$special_characters{"}"} = "\\}";
$special_characters{"#"} = "\\#";
$special_characters{"%"} = "\\%";
$special_characters{"&"} = "\\&";
my $string = '$foobar';
foreach my $char (keys %special_characters) {
$string =~ s/$char/$special_characters{$char}/g;
}
print $string;
quotemeta()
ors/\Q$char\E/...
You should remember do this for every $variable, since regexps interpolate them. – Hagiology