neeha has asked for the wisdom of the Perl Monks concerning the following question:

Hi Experts,
The below code does some substitution
$line =~ s#$methodname\(($2)\)#private $methodname($2)#g
Here $2 is the values in the parameters.
If the value of $2 is "String str". It works fine
But if value of $2 is "String str[]".
Unmatched [ in regex; exception occurs.
THis happens only with Square brackets
How can i do the substitution of a string with Square brackets.
Waiting for ur replies.
Thanks,
Swarna.

Replies are listed 'Best First'.
Re: substitution of a string with Square brackets.
by GrandFather (Saint) on Mar 20, 2006 at 10:41 UTC

    Use \Q and \E to quote the string:

    $line =~ s#$methodname\((\Q$2\E)\)#private $methodname($2)#g

    DWIM is Perl's answer to Gödel
Re: substitution of a string with Square brackets.
by salva (Canon) on Mar 20, 2006 at 10:31 UTC
    use quotemeta to escape any special char in $2:
    my $args = quotemeta $2; $line =~ s#$methodname\(($args)\)#private $methodname($1)#g;
Re: substitution of a string with Square brackets.
by Samy_rio (Vicar) on Mar 20, 2006 at 10:37 UTC

    Hi, Try like this,

    Untested

    $line =~ s#$methodname\((\Q$2\E)\)#private $methodname($2)#g

    Regards,
    Velusamy R.


    eval"print uc\"\\c$_\""for split'','j)@,/6%@0%2,`e@3!-9v2)/@|6%,53!-9@2~j';

Re: substitution of a string with Square brackets.
by Melly (Chaplain) on Mar 20, 2006 at 10:38 UTC
    s#$methodname\((\Q$2\E)\)#private $methodname($2)#g

    should fix it... although I am somewhat suspicious as to what you are doing with $2...

    Tom Melly, tom@tomandlu.co.uk
Re: substitution of a string with Square brackets.
by mickeyn (Priest) on Mar 20, 2006 at 10:38 UTC
    you should wrap $2 with quotes, i.e. \Q$2\E
    $line =~ s#$methodname\((\Q$2\E)\)#private $methodname(\Q$2\E)#g
    Enjoy,
    Mickey