【发布时间】:2020-11-06 11:04:32
【问题描述】:
我从外部来源获得一堆文本,将其保存在一个变量中,然后将该变量显示为更大的 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.
谷歌搜索将我带到this question。当我尝试在答案中使用数组和for循环时,它没有效果。
如何让块输出完全按原样显示变量?
【问题讨论】:
-
我想 Perl 在这里像 PHP 一样工作,并在您创建字符串的那一刻替换变量。因此,如果您在创建字符串时不对其进行转义,则实际字符串中永远不会出现
$字符。