On Jan 2, 2008 11:11 PM, Murali <[EMAIL PROTECTED]> wrote:
> Hi,
>
> I have a scalar variable $x whose value is "a(b"
>
> I am trying to replace the paranthesis with a backslash followed by
> parenthesis, I mean, ( to \(
>
> $x =~ s/\(/\\(/g;
>
> However this is making $x as "a\\(b" which is not what I want.
snip

One of those two statements is false.  If $x holds only "a(b" then $x
=~ s/\(/\\(/g will result in $x holding "a\(b"

perl -le '$x = "a(b"; print $x; $x =~ s/\(/\\(/; print $x'

prints

a(b
a\(b

So, if you are seeing 'a\\(b' then one of two things is occurring:
1. you aren't really seeing 'a\\(b', you just think it is there
because that is what is in the replacement string
2. $x doesn't just contain "a(b"

I would suggest printing the variable to the screen to see if it
really contains 'a\\(b'.  If it doesn't (and I expect that it
doesn't), I would suggest going back and rereading the Quote and
Quote-like Operators section in perldoc perlop or
http://perldoc.perl.org/perlop.html#Quote-and-Quote-like-Operators to
understand why a \\ in the second part of the substitutionis turning
into a \ in the output (hint: it has to do with interpolation and
escapes).

If you do indeed see a second backslash in the output then $x must not
have contained what you said it contained.  Go back an take a better
look at it.  If it contains something like 'a(b a\(b' then the
substitution will turn it into 'a\(b a\\(b'.  You can use the
zero-width negative look-behind assertion* that John mentions in his
email to prevent it from prepending a \ to a ( that is already
preceded by a \.

* read more in perldoc perlre or
http://perldoc.perl.org/perlre.html#Look-Around-Assertions

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/


Reply via email to