Inplace replacement in a file through a perl script

安稳与你 提交于 2019-12-12 12:55:24

问题


I wanted to know how to replace a string in place using a perl script rathere than a command line. I searched through web andI tried below things.

I have a file:

> cat temp
this is one
>

And i have a below script that i wrote:

> 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;

But when i try to execute(>perl temp.pl) this it just hangs and the file is also not getting updated. The version of perl i am using is 5.8.4 Also the command line thing(perl -pi -e 's/one/1/g' temp) works perfectly. Is there anything wrong that I am doing?


回答1:


You need to change global @ARGV, and with my you made lexical @ARGV

use strict;
use warnings;

@ARGV=('temp');

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


来源:https://stackoverflow.com/questions/18998180/inplace-replacement-in-a-file-through-a-perl-script

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!