簡體   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