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

New User

Sep 22, 2009, 10:30 AM

Views: 5104
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.


Sep 22, 2009, 11:28 AM

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

Hi aatucker3,

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

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



New User

Sep 22, 2009, 11:33 AM

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

Sweet, thanks 1arryb :)

Veteran / Moderator

Sep 22, 2009, 11:45 AM

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

The regex you posted worked for me.

[root@rkb-2 ~]# cat test.pl 

use strict;
use warnings;

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

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

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

New User

Sep 22, 2009, 12:02 PM

Views: 5090
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 ( 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.