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

Hi,

I have written a perl program that grabs text patterns like so:-

if ($rpt[$ln] =~ /^\sStartpoint/ { @ptlalsp = split(/\s+/,$rpt[$ln]); $ptsp = $ptlalsp[2]; #get name do { $ln++; } until ($rpt[$ln] =~ /$ptsp/); #name will show up #again...increment #$ln until found #other stuff... }
...but every so often $ptsp possesses a [ or ], which messes up my pattern matching. How do I treat [ and ] as literal characters and not special characters?

Thanks,
-Fiddler42

Replies are listed 'Best First'.
Re: How to deal with [ and ] chars
by Ven'Tatsu (Deacon) on May 04, 2004 at 19:16 UTC
    Try /\Q$ptsp\E/
    from the perlre man page:
    \E end case modification (think vi)
    \Q quote (disable) pattern metacharacters till \E
Re: How to deal with [ and ] chars
by Zaxo (Archbishop) on May 04, 2004 at 20:28 UTC

    An alternative to ++Ven'Tatsu's answer is to apply quotemeta before the interpolation,     $ptsp = quotemeta $ptlalsp[2];        #get name

    After Compline,
    Zaxo

Re: How to deal with [ and ] chars
by geekgrrl (Pilgrim) on May 04, 2004 at 19:34 UTC
    i would say to do a regex on $ptsp and insert backslashes before the square braces.
    ($ptsp = $ptlalsp[2]) =~ s/(\[|\])/\\$1/g;