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

String substitution

by abhay180 (Acolyte)
on Jul 12, 2010 at 16:50 UTC ( #849049=perlquestion: print w/replies, xml ) Need Help??
abhay180 has asked for the wisdom of the Perl Monks concerning the following question:

Why is the following substitution of $expr (with $n_expr) in $line not working?
print "BEFORE:LINE = $line,EXPR= $expr,NEW_EXPR= $n_expr\n"; $line =~ s/$expr/$n_expr/; print "AFTER:LINE = $line,EXPR= $expr,NEW_EXPR= $n_expr\n";
The o/p of above is: BEFORE:LINE = input [`CLW:::0] abc;,EXPR = [`CLW:::0], NEW_EXPR= [$CLW +:0] AFTER:LINE = input [`CLW:::0] abc;,EXPR = [`CLW:::0], NEW_EXPR= [$CLW: +0]
The PERL-version is : V5.8.8; OS is: x86_64-linux-thread-multi

Replies are listed 'Best First'.
Re: String substitution
by Corion (Pope) on Jul 12, 2010 at 16:55 UTC

    Your search string is interpreted as a regular expression, and it contains regular expression meta characters. See perlre. Maybe you wanted to use quotemeta or \Q|?

    $line =~ s/\Q$expr/$n_expr/;
      Thanks a lot. That helps. Indeed i seem to have forgotten the basic rules of substitution :-)
Re: String substitution
by moritz (Cardinal) on Jul 12, 2010 at 16:54 UTC
    Because s/// treats the first string is a regex, and not all regexes match their own textual representation. Hint: [...] has a special meaning, see perlretut.

    You can avoid that with \Q$EXPR\E.

    Perl 6 - links to (nearly) everything that is Perl 6.

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://849049]
Approved by moritz
help
Chatterbox?
[Discipulus]: shmem the first time I was in germany I was so smart to learn by heart the address of the hostel: Einbahnstraße..
[Discipulus]: james28909 you are welcome
james28909 doesnt drink much alcohol
james28909 does enjoy blazing up though
james28909 also walks around hunting for his cell phone while using its flashlight function

How do I use this? | Other CB clients
Other Users?
Others lurking in the Monastery: (5)
As of 2018-05-20 16:14 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Notices?