Question

How can I replace the backslash inside the 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
Was it helpful?

Solution

Because you're using this inside of a regex -- you probably want quotemeta() or \Q 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";

OTHER TIPS

If you set $re = 'a\cc';, it would work. The backslash is not getting interpolated as you expect when you include it in the regex as a variable: it is being used literally in the substitution.

Alternatively you could define the string with double quotes, but that's not a good practice. It's better to always use single quotes in your strings unless you explicitly want to interpolate something in the content -- it saves an infitesimal amount of processing, but it is a hint to the reader as to what you the programmer intended.

The problem is that you're using single quotes to define $re. That means that when you use it in the search pattern it looks for two slashes.

Single quotes tell Perl not to interpolate the strings, but to use the raw characters instead. Each slash is taken literally and as an escape.

Compare:

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

When you print them out you'll see:

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

a\\cc
a\cc

On the other hand, when you use the string directly in the regex, it's interpolated, so you need one slash to act as an escape, and another to be what you're escaping.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top