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

Hi, I have a basic question on regexes. Consider the following regex:
/^$string/;
How can I tell Perl not to interpret meta-characters in $string such that I could say, for example:
$string = "\$foo"; /^$string/;
... and have the effect be that $_ is left-anchor searched for the uninterpolated text literal "$foo"? Thanks.

Replies are listed 'Best First'.
Re: Basic regex question
by runrig (Abbot) on Jul 18, 2007 at 19:26 UTC
    quotemeta (from perlfunc) or \Q (from perlre) (they are the same thing just used in different places):
    $string = quotemeta('$foo'); /^$string/; # Or $string = '$foo'; /\Q$string/;
Re: Basic regex question
by FunkyMonk (Bishop) on Jul 18, 2007 at 19:27 UTC
    You can either use the \Q...\E construct (documented in perlre) within a regex, or the quotemeta function call.

    #\E not necessary at end of pattern /^\Q$string/ and print "A match!\n"; #or, same thing $string=quotemeta $string; /^$string/ and print "A match!\n";

    update: Re-slanted my slashes. Thanks corion.