Nik Nik - 4 months ago 15
Perl Question

How to handle special characters in perl pie find replace

I have the following text in a file:

prompt **********************************************************************************
prompt ** Start
prompt **********************************************************************************
prompt **
prompt ** Calling: FILE
prompt **
prompt **
@@FOLDER\FILE
prompt **
prompt ** commit
commit;
prompt **
prompt **
prompt **
prompt **********************************************************************************
prompt ** End
prompt **********************************************************************************


When I do

$ perl -pi -e "s/FILE/$file/g" ./tmp.sql;


It replaces all instances of the word FILE with whatever I have in $file, but when I call

$ perl -pi -e "s/FOLDER/$folder/g" ./tmp.sql;


Which just has the folder string, it coughs up, doesn't replace anything and the shell where I am calling it from spits out this stuff:

Execution of -e aborted due to compilation errors.
Unquoted string "g" may clash with future reserved word at -e line 1.
Unknown regexp modifier "/R" at -e line 1, at end of line
Unknown regexp modifier "/F" at -e line 1, at end of line
Unknown regexp modifier "/5" at -e line 1, at end of line
Unknown regexp modifier "/4" at -e line 1, at end of line
Unknown regexp modifier "/7" at -e line 1, at end of line
Unknown regexp modifier "/5" at -e line 1, at end of line
Unknown regexp modifier "/6" at -e line 1, at end of line
Unknown regexp modifier "/_" at -e line 1, at end of line
Unknown regexp modifier "/2" at -e line 1, at end of line


Anyone know what gives?

Answer

Slashes embedded in the folder variable are prematurely terminating the substitution

The easiest solution is to change the delimiters. Something like this should work

$ perl -pi -e "s{FOLDER}{$folder}g" tmp.sql