【问题标题】:Inplace replacement in a file through a perl script通过 perl 脚本在文件中就地替换
【发布时间】:2013-09-25 06:54:26
【问题描述】:

我想知道如何使用 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;

但是当我尝试执行(&gt;perl temp.pl) 时它只是挂起并且文件也没有得到更新。 我使用的 perl 版本是 5.8.4 命令行的东西(perl -pi -e 's/one/1/g' temp)也可以完美运行。 我做错了什么吗?

【问题讨论】:

    标签: perl edit-in-place


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 2016-11-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-31
      • 1970-01-01
      • 2012-01-30
      相关资源
      最近更新 更多