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

String substitution

by abhay180 (Sexton)
on Jul 12, 2010 at 16:50 UTC ( [id://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 (Patriarch) 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
Domain Nodelet?
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?Last hourOther CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (4)
As of 2024-04-25 12:01 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found