【问题标题】:Trouble escaping dollar sign in Perl在 Perl 中转义美元符号时遇到问题
【发布时间】: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 一样工作,并在您创建字符串的那一刻替换变量。因此,如果您在创建字符串时不对其进行转义,则实际字符串中永远不会出现 $ 字符。

标签: regex perl escaping


【解决方案1】:

这就是我想看到的:

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.

【讨论】:

  • 另外,对字符串使用single quotes 不会插入变量。
【解决方案2】:

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

至于您的正则表达式,这很奇怪。它正在寻找$ 并用$ 替换它们。如果你想要反斜杠,你也必须转义它们。

【讨论】:

  • 你是对的,双引号意味着它从不包含$,所以没有正则表达式可以工作。我熟悉单引号和双引号之间的区别,但不知何故,当它是源字符串的一部分时,我从未想过。谢谢!
【解决方案3】:

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

这应该是:

# 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中也是如此。

【讨论】:

    猜你喜欢
    • 2019-10-07
    • 2015-06-17
    • 2021-07-01
    • 1970-01-01
    • 2022-11-22
    • 1970-01-01
    • 2023-03-03
    • 1970-01-01
    相关资源
    最近更新 更多