Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer

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?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://849049]
Approved by moritz
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others scrutinizing the Monastery: (4)
As of 2017-10-20 03:50 GMT
Find Nodes?
    Voting Booth?
    My fridge is mostly full of:

    Results (258 votes). Check out past polls.