通过perl脚本在文件中进行替换

时间:2013-09-25 06:54:26

标签: perl edit-in-place

我想知道如何使用perl脚本来替换字符串而不是命令行。 我通过网络搜索,并尝试了以下内容。

我有一个文件:

> cat temp
this is one
>

我写了一个下面的脚本:

> cat temp.pl
#!/usr/bin/perl -i.bak
use strict;
use warnings;
my @ARGV=('temp');
$^I = '.bak';
my %hash=("one"=>"1");
{
    while (<>) {
        s/(one)/$hash{$1}/g;
        print;
    }
}
exit;

但是当我尝试执行(>perl temp.pl)时,它只是挂起而且文件也没有得到更新。 我使用的perl版本是5.8.4 命令行事物(perl -pi -e 's/one/1/g' temp)也很有效。 我有什么不对的吗?

1 个答案:

答案 0 :(得分:4)

您需要更改全局@ARGV,并使用my更改词汇@ARGV

use strict;
use warnings;

@ARGV=('temp');

$^I = '.bak';
my %hash=("one"=>"1");
while (<>) {
        s/(one)/$hash{$1}/g;
        print;
}