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

Greetings chipmunk,

Thanks for your help. Very good information. I have one follow-up question: Is there a way to default allow all escape sequences? In another words, allow $changefrom and $changeto to be interpolated exactly the same way? That way, a user could run the script and change "\n" to "\t" literally.

Gryphon.

Replies are listed 'Best First'.
Re: Re: Re: Re: Change utility; code optimization
by chipmunk (Parson) on Feb 13, 2001 at 10:02 UTC
    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.