Home: Perl Programming Help: Intermediate:
Escaping closed parenthesis.



aatucker3
New User

Sep 22, 2009, 10:30 AM


Views: 5041
Escaping closed parenthesis.

I'm trying to substitute the character ) with the characters \)

The code below won't work and I simply can't figure out why.

my $sReferenceHeading = "Something)";
$sReferenceHeading =~ s/\)/\\\)/g;

I expect the output to be "Something\)" but it ends up being "Something\\)"

Please advise.


1arryb
User

Sep 22, 2009, 11:28 AM


Views: 5038
Re: [aatucker3] Escaping closed parenthesis.

Hi aatucker3,

Try escaping the paren with square brackets (i.e, treating them as a 1 character list):

Code
$ perl -e 'my $str = "Something)"; $str =~ s/[)]/\\)/; print "str = \"$str\"\n";' 
str = "Something\)"
$


Cheers,

Larry


aatucker3
New User

Sep 22, 2009, 11:33 AM


Views: 5035
Re: [1arryb] Escaping closed parenthesis.

Sweet, thanks 1arryb :)


FishMonger
Veteran / Moderator

Sep 22, 2009, 11:45 AM


Views: 5031
Re: [aatucker3] Escaping closed parenthesis.

The regex you posted worked for me.


Code
[root@rkb-2 ~]# cat test.pl 
#!/usr/bin/perl

use strict;
use warnings;

my $sReferenceHeading = "Something)";
$sReferenceHeading =~ s/\)/\\\)/g;
print $sReferenceHeading;

[root@rkb-2 ~]# ./test.pl
Something\)


You must have had an extra (i.e., 4th) backslash in the regex when you tested.


aatucker3
New User

Sep 22, 2009, 12:02 PM


Views: 5027
Re: [FishMonger] Escaping closed parenthesis.

Thanks for the response FishMonger. I'll have to look at the version of perl I was using on the MAC. I just downloaded and installed the latest version of ActivePerl (5.10.1.1006) on my PC and it works both ways. I'll update this thread once I find out the version I was using. At least I know I'm not crazy now. Oh, and I DID check the variable before and after the swap to make sure there was no bad data.