繁体   English   中英

无法在 Perl 中转义美元符号

[英]Trouble escaping dollar sign in Perl

我从外部来源获取一堆文本,将其保存在一个变量中,然后将该变量显示为更大的 HTML 块的一部分。 我需要按原样显示它,美元符号给我带来了麻烦。

这是设置:

# get the incoming text
my $inputText = "This is a $-, as in $100. It is not a 0.";

print <<"OUTPUT";
before-regex: $inputText
OUTPUT

# this regex seems to have no effect
$inputText =~ s/\$/\$/g;

print <<"OUTPUT";
after-regex:  $inputText
OUTPUT

在现实生活中,这些print块是直接插入变量的更大的 HTML 块。

我尝试使用s/\\$/\\$/g转义美元符号,因为我的理解是第一个\\$转义正则表达式,因此它搜索$ ,第二个\\$是插入的内容,然后转义 Perl 以便它只显示$ 但我无法让它工作。

这是我得到的:

before-regex: This is a 0, as in . It is not a 0.
after-regex:  This is a 0, as in . It is not a 0.

这就是我想看到的:

before-regex: This is a 0, as in . It is not a 0.
after-regex:  This is a $-, as in $100. It is not a 0.

谷歌搜索让我想到了这个问题 当我尝试在答案中使用数组和 for 循环时,它没有效果。

如何让块输出完全按原样显示变量?

当你用双引号构造一个字符串时,变量替换会立即发生。 在这种情况下,您的字符串永远不会包含$字符。 如果您希望$出现在字符串中,请使用单引号或对其进行转义,并且请注意,如果您这样做,您将不会获得任何变量替换。

至于你的正则表达式,这很奇怪。 它正在寻找$ ,并取代它们$ 如果你想要反斜杠,你也必须逃避它们。

这就是我想看到的:

 before-regex: This is a 0, as in . It is not a 0. after-regex: This is a $-, as in $100. It is not a 0.

嗯,好吧,我不确定一般情况是什么,但也许以下方法可以:

s/0/\$-/;
s/in \K/\$100/;

或者你的意思是开始

 my $inputText = "This is a \$-, as in \$100. It is not a 0.";
 # Produces the string: This is a $-, as in $100. It is not a 0.

或者

 my $inputText = 'This is a $-, as in $100. It is not a 0.';
 # Produces the string: This is a $-, as in $100. It is not a 0.

您的错误是在变量声明中使用双引号而不是单引号。

这应该是:

# get the incoming text
my $inputText = 'This is a $-, as in $100. It is not a 0.';

了解 ' 和 " 和 ` 之间的区别。请参阅http://mywiki.wooledge.org/Quoteshttp://wiki.bash-hackers.org/syntax/words

这是针对 shell 的,但在 Perl 中也是如此。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM