Beefy Boxes and Bandwidth Generously Provided by pair Networks vroom
Problems? Is your data what you think it is?
 
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

Comment on String substitution
Select or Download Code
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.
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 :-)

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?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others perusing the Monastery: (9)
As of 2014-04-23 10:44 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    April first is:







    Results (541 votes), past polls