Regex 使用正则表达式的变量替换

Regex 使用正则表达式的变量替换,regex,perl,Regex,Perl,我想用perl替换文件(temp.txt)中的一个变量 temp.txt Hi $test. How are you?? 现在我想替换变量$test。我试过的代码如下: open my $filename, "<", temp.txt or die $!; while (<$filename>) { s/$test/'abc'/g; print; } 打开我的$filename,“您需要转义$,因为Perl认为它是一个变量: use warnings; u

我想用perl替换文件(temp.txt)中的一个变量

temp.txt

Hi  $test. How are you??
现在我想替换变量
$test
。我试过的代码如下:

open my $filename, "<", temp.txt or die $!;

while (<$filename>) 
{ 
 s/$test/'abc'/g;
 print;
}   

打开我的$filename,“您需要转义
$
,因为Perl认为它是一个变量:

use warnings;
use strict;

while (<DATA>) {
    s/\$test/'abc'/g;
    print;
}

__DATA__
Hi  $test. How are you??
使用警告;
严格使用;
而(){
s/\$test/'abc'/g;
印刷品;
}
__资料__
嗨$test.你好吗??

您是否正试图替换字符串
$test
,或名为
$test
的变量中包含的字符串?因为您的代码正在执行后者。
使用严格;使用警告;
将通知您此错误。此外,您永远不要说“它不工作”没有说明它是如何工作的。我试图用它的值替换“$test”。我基本上想用“abc”替换文件中的变量$test。您需要在模式中转义
$
$
在正则表达式中表示行尾。要匹配文字美元符号,请对其进行反斜杠转义,或将其放入字符类中
s/\$test/'abc'/
s/[$]test/'abc'/