tomaytotomato
tomaytotomato

Reputation: 4028

Search and replace in file in Perl?

Following from this example here on another SO question.

I added the following code to my basic perl script.

#!/usr/bin/perl

$^I = '.bak'; # create a backup copy 

while (<>) 
{
   s/NewProdId/$ARGV[1]/g; # do the replacement
   s/PortId/$ARGV[2]/g; # do the replacement
   s/AssemblyId/$ARGV[3]/g; # do the replacement
   print; # print to the modified file
}

However when I call the perl script with more than one argument, it breaks. It appears to e mistaking my other argument for a filename for it to open.

Can't open 1-THU-71: No such file or directory at ./process.pl line 11, <> line 37.

Can't open 1-5XJ0DF: No such file or directory at ./process.pl line 11, <> line 37.

Can't open 1-3F0MB9: No such file or directory at ./process.pl line 11, <> line 37.

My bash script call is as such:

./process.pl "test.txt" $values

What am I doing wrong here?

Upvotes: 2

Views: 247

Answers (1)

mpapec
mpapec

Reputation: 50667

The diamond operator <> tries to open all the files mentioned in the arguments. You should remove elements from @ARGV which are not file names:

my @ar = @ARGV;
@ARGV = shift @ARGV;

while (<>) 
{
   s/NewProdId/$ar[1]/g; # do the replacement
   s/PortId/$ar[2]/g; # do the replacement
   s/AssemblyId/$ar[3]/g; # do the replacement
   print; # print to the modified file
}

Upvotes: 5

Related Questions