Beefy Boxes and Bandwidth Generously Provided by pair Networks
"be consistent"
 
PerlMonks  

string interpolation in RE

by asinghvi (Acolyte)
on Jan 05, 2002 at 03:38 UTC ( #136416=perlquestion: print w/replies, xml ) Need Help??

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.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://136416]
Approved by root
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others taking refuge in the Monastery: (1)
As of 2021-09-19 23:04 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?