使用 perl 替换命令用反斜杠替换文本

Replacing text with backslashes with perl substitution command

所以我正在编写一个 perl 脚本,该脚本对输入执行替换命令,并且输入将带有反斜杠。所以只需用新文本替换一些文本

例如,如果输入是

"\text"

我可能会输出

"newText"

请注意,斜杠已被删除。

下面是一些代码:

$oldText = "\Text";

while (<STDIN>) {                
    $ln = $_;                     
    $ln2 = $_;
    $ln2 =~ s/\Text/newText/;  
    $ln =~ s/$oldText/newText/;
}
print "$ln\n";
print "$ln2\n";

当输入为"Text"时,输出为

\newText #Incorrect because the \ is still there

newText #Correct

谁能解释为什么使用字符串而不是变量将输出更改为我想要的?我知道 \ 取消引用以下字符,这可能是问题的根源。但我不明白为什么使用变量会改变输出。将变量 oldText 更改为 "\text" 不会更改输出。

使用 warnings 会告诉你:

Unrecognized escape \T passed through in regex; marked by <-- HERE in m/\T <-- HERE ext/ at ...

$oldText = "\Text" 将字符串 \Text 分配给 $oldText,因此这两个替换并不等价。使用\Q(见quotemeta)引用一个变量的内容:

$ln =~ s/\Q$oldText/newText/;