在 Perl 中的变量中用反斜杠替换文本 [英] Text replacement with backslash in a variable in Perl

查看:39
本文介绍了在 Perl 中的变量中用反斜杠替换文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何替换变量中的反斜杠?

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";

输出:

a\cc\ee
Work\ee

推荐答案

因为你在正则表达式中使用它 -- 你可能想要 quotemeta()\Q\E(见 perldoc perlre)

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";

这篇关于在 Perl 中的变量中用反斜杠替换文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆