joe
joe

Reputation: 3

using variable in search n replaces in perl

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?

Upvotes: 0

Views: 192

Answers (1)

mpapec
mpapec

Reputation: 50637

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

Upvotes: 1

Related Questions