in reply to Re: Re: Re: Change utility; code optimization
in thread Change utility; code optimization

I can't think of a good quick and easy way to interpolate the escape sequences.

Here's a simple but unsafe way: s/$changefrom/qq{"$changeto"}/giee; The right-hand side is evaluated twice, so $changeto gets interpolated and then its value gets interpolated. This is unsafe because $changeto could contain $ or @, giving access to variables in your program, or "s, which would either cause a syntax error or allow the evaluation of arbitrary code. In a script where you know the value of $changeto, it's a useful idiom.

Here's a safer way:

$changeto =~ s,(?<!\\)((?:\\\\)*)([\$\@\"]),$1\\$2,g; s/$changefrom/qq{"$changeto"}/giee;
The first line puts a backslash before each $, @, and " which is not already escaped. A character is already escaped if it's preceeded by an odd number of backslashes. I think that those three characters are the only ones that need to be escaped. However, I could be overlooking something, which I hope someone will point out if I am.

The safest approach is to turn on taint-checking, and carefully untaint $changeto to make sure it contains a safe replacement string.