Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask
 
PerlMonks  

substitution of a string with Square brackets.

by neeha (Novice)
on Mar 20, 2006 at 10:23 UTC ( #537905=perlquestion: print w/replies, xml ) Need Help??
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 (Sage) 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 (Abbot) 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 (Hermit) 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

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://537905]
Approved by Corion
help
Chatterbox?
Jar. Jar!...

How do I use this? | Other CB clients
Other Users?
Others chanting in the Monastery: (2)
As of 2017-09-23 18:33 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    During the recent solar eclipse, I:









    Results (273 votes). Check out past polls.

    Notices?