使用Regex进行可变替换

时间:2014-04-14 18:41:13

标签: 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;
}   

它不起作用。谁能告诉我我做错了什么?

1 个答案:

答案 0 :(得分:3)

你需要转义$,因为Perl认为它是一个变量:

use warnings;
use strict;

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

__DATA__
Hi  $test. How are you??
相关问题