在佩尔(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.

谷歌搜索使我解决了这个问题。当我尝试使用阵列并在答案中循环时,它没有效果。

如何获得块输出以完全显示变量?

当您构造带有双引号的字符串时,变量替换会立即发生。在这种情况下,您的字符串将永远不会包含$字符。如果您希望$出现在字符串中,请使用单价或逃脱它,并且请注意,如果这样做,您将不会获得任何变量。

至于您的正则是奇怪的。它正在寻找$并用$代替它们。如果您想要后斜切,也必须逃脱。

这是我想看到的:

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.';

学习'和`。

这是针对外壳的,但是在perl中是相同的。

最新更新