http://www.perlmonks.org?node_id=136416

asinghvi has asked for the wisdom of the Perl Monks concerning the following question:

I am trying to do a substitution using RE but it is not yielding correct results
my initial_string is:
$initial_string = "REPLACE";
my replace_with string is:
$replace_with_string = '\\decs17\dq';
When I do: $initial_string =~ s{REPLACE}{$replace_with_string};It gives me initial_string as
\decs17\dq
Note that the double back slash is missing. When I do:
$initial_string =~ s{REPLACE}{\Q$replace_with_string\E};
It makes more mess by making intial_string as
\\decs17\\dq
What should I use with the substitution. Help is appreciated.!!

Replies are listed 'Best First'.
(tye)Re: string interpolation in RE
by tye (Sage) on Jan 05, 2002 at 03:47 UTC

    \ is special to all forms of quoting in Perl except for single-quoted here-docs. If you want two \'s in Perl then you need to put in four \'s:

    print '\\decs17\dq'; # prints \decs17\dq print '\\\\decs17\dq'; # prints \\decs17\dq print '\\\\decs17\\dq'; # also prints \\decs17\dq
    Note that I tend to use the last version because I find that it discourages me from getting confused into thinking that \ isn't special inside of single quotes and so I'm less likely to run into the problem you just did. (:

            - tye (but my friends call me "Tye")
Re: string interpolation in RE
by jonjacobmoon (Pilgrim) on Jan 05, 2002 at 04:26 UTC
    I would look into using quotemeta. See it on pg 201 of the Camel book, 2nd edition. Update: I am wrong. Ignore my answer. When Tye flagged me on it, I ran a test script and got:

    \\decs17\\dq

    which is not what you wanted. Sorry.