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

How do I escape the ^ metacharacter in a variable? I'm using perl version 4.0.1.8. I've tried using \Q...\E but it doesn't work.
$a="xxx^1.0"; $b="xxx^1.0 yyyy zzz"; if($b=~/\Q$a\E/) { print "worked\n"; } else { print "nope\n"; } run test: nope

Replies are listed 'Best First'.
(tye)Re: Escaping metacharacters
by tye (Sage) on Dec 12, 2002 at 21:26 UTC

    Do

    $a =~ s/(\W)/\\\1/g; # or $a =~ s/(\W)/\\$1/g;
    before your "if" line. I'd test this but I've lost track of my Perl4 executable. I redownloaded perl4 and both of those work for me (if you also drop the \Q and \E that I forgot to mention).

            - tye
      Thanks. I knew I could modify the var but I wanted to do it without the extra step. Maybe it's not possible in perl4.
Re: Escaping metacharacters
by Enlil (Parson) on Dec 12, 2002 at 21:20 UTC
    I believe this was not working until perl 5.0.

    As per the docs:

    Variables may now be interpolated literally into a pattern by prefixing them with \Q, which works just like \U, but backwhacks non-alphanumerics instead. There is also a corresponding quotemeta function.

    On a side note though you might not want to get in the habit of using $a or $b as variable names as sooner or later you might want to sort something.

    -enlil

Re: Escaping metacharacters
by logan (Curate) on Dec 12, 2002 at 21:20 UTC
    I have to ask. Why are you using perl version 4.0.1.8? I've never been a "Must. Use. Latest. Version." guy, but hanging on to Perl 4 when we're so close to shipping Perl 6 seems like an odd choice.

    -Logan
    "What do I want? I'm an American. I want more."

      Because the app I'm using installs this old version and to get a new version installed on the server is next to impossible.
Re: Escaping metacharacters
by BrowserUk (Patriarch) on Dec 12, 2002 at 21:15 UTC

    Works for me?

    C:\test>perl $a="xxx^1.0"; $b="xxx^1.0 yyyy zzz"; if($b=~/\Q$a\E/) { print "worked\n"; } else { print "nope\n"; } ^Z worked C:\test>

    Examine what is said, not who speaks.

Re: Escaping metacharacters
by gnu@perl (Pilgrim) on Dec 12, 2002 at 21:14 UTC
    I just cut and pasted your code into my Solaris box running Perl 5.6.1 and it worked fine. What version of perl are you using and what OS?

    UPDATE: Sorry, stupid mistake. Didn't see that the version of perl was stated RIGHT IN THE QUESTION!.