perledit-in-place

Inplace replacement in a file through a perl script


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?


Solution

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