in reply to Substituting literal strings for escape characters

You are going in the right direction with the evalled substitution, but consider what you end up with: eval "\n", which is much the same as

eval { }

The obvious next thing to try is adding the quotes:

s/(\\\w)/"$1"/eg;
but that doesn't do the trick, and brainfade prevents me from explaining why. :(

Adding a second evaluation step is enough to achieve the desired result:

s/(\\\w)/qq{"$1"}/eeg;

Hugo

Replies are listed 'Best First'.
Re: Re: Substituting literal strings for escape characters
by xmath (Hermit) on Feb 18, 2003 at 15:54 UTC
    That contains a bug:

    The input string:  \\n should be interpreted as:  \n (as in, the backslash escapes the backslash) but in your case, it becomes a backslash followed by a newline.

    The solution is:  s/(\\.)/qq["$1"]/eegs

    Btw, the reason "$1"/e isn't sufficient is because when using /e it doesn't interpolate before evaluating, so the expression really becomes "$1" which is identical to $1 - no change happens at all.

    With qq["$1"]/ee however it'll interpolate $1 into a double-quoted string the first time, and then evaluates that double-quoted string

    •Update: to also support multi-char escapes:

    s/(\\(?:\d{1,3}|x[a-fA-F\d]{1,2}|x\{\w*\}|c.|N\{\w*\}|.))/qq["$1"]/eeg +s
    (not fully tested)