0

I'm facing issues while trying to use the search n replace option in perl.

This is not an issue in the unix but appears only in windows. I'm using variable to search a file and replace it with desired string. Also I'm using it in a one liner in a perl script, so it just adds to the problem!

$oldstring = 1234;
$newstring = 6789;

system("perl -pi.back e s/$oldstring/$newstring/g $filename");

I'm retrieving the file names in a directory from an array and passing them as input to the one-liner. There seems to be no change in the output files, but it does not report any warnings or failures either.

I tried the following too,

system("perl -pi.back e 's/$oldstring/$newstring/g' $filename");

Why is the search n replace not working as expected?

joe
  • 3
  • 3
  • This is not valid perl `$oldstring = 1234 $newstring = 6789`. Missing a `;` at the end of each line. Please post the actual code you are running. – Dr.Avalanche Feb 12 '14 at 10:13
  • 1
    @ztirom - thanks for the formatting edit – joe Feb 12 '14 at 10:15
  • @Dr.Avalanche - sorry this is my first post here. It is a big script, I was just trying to post only the relevant part here. still it was mistake. – joe Feb 12 '14 at 10:16

1 Answers1

1

You need appropriate quoting for system() and for command line,

system(qq(perl -pi.back -e "s/$oldstring/$newstring/g" $filename));

or use simpler and more efficient system without calling shell,

system("perl", "-pi.back", "-e", "s/$oldstring/$newstring/g", $filename);
mpapec
  • 50,217
  • 8
  • 67
  • 127
  • thanks for your solution. Does this one liner not work in windows without creating a back file? There seems to be no issues in unix though. – joe Feb 12 '14 at 10:28
  • @joe check http://stackoverflow.com/questions/2616865/why-do-i-have-to-specify-the-i-switch-with-a-backup-extension-when-using-active – mpapec Feb 12 '14 at 10:34