Replacing backslash text in a Perl variable

How to replace backslash inside a variable?

$string = 'a\cc\ee';
$re = 'a\\cc';
$rep = "Work";

#doesnt work in variable
$string =~ s/$re/$rep/og;
print $string."\n";

#work with String
$string =~ s/a\\cc/$rep/og;
print $string."\n";

output:

a\cc\ee
Work\ee
+3
source share
3 answers

Since you use this inside a regex, you probably want quotemeta()either \Qand and \E(see perldoc perlre)

perl -E'say quotemeta( q[a/asf$#@ , d] )'

# prints: a\/asf\$\#\@\ \,\ d

# Or, with `\Q`, and `\E`
$string =~ s/\Q$re\E/$rep/og;
print $string."\n";
+9
source

If you install $re = 'a\cc';, it will work. The backslash does not get interpolated, as you would expect when you include it in a regular expression as a variable: it is used literally in substitution.

, . , - , - , , .

+2

, $re. , , , .

Perl , . .

:

$re0 = 'a\\cc';
$re1 = "a\\cc";

, :

print $re0."\n".$re1."\n";

a\\cc
a\cc

, , , , , - , .

0

Source: https://habr.com/ru/post/1748410/


All Articles