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

need help with something probably fairly simple. i am using m to search for a variable $string, like this:

$LINES[$i] =~ /$string/

however $string contains characters like + and ^ that are evaluated by the m// function after $string is interpolated, and I do not want this to happen.

On the perlman page on this website it says to use the /Q to prevent this second level of interpolation, but I tried using:

/\Q$string\E/ and /$\Qstring\E/
and also I tried escaping the non-word characters (another suggestion I found on another website) before I performed the match, like this:

$string =~ s/(W)/\\$1/g

but none of these worked b/c every time I tried it it gave me the same error:

Quantifier follows nothing before HERE mark in regex m/+ << HERE 5^7/

where $string in this instance was +5^7
does anybody know how to fix this?

20031124 Edit by BazB: Changed title from 'newbie question'

Replies are listed 'Best First'.
Re: Quoting metacharacters in regexen
by Roger (Parson) on Nov 24, 2003 at 00:38 UTC
    I have written the following demo program but was delayed for almost an hour because I had to attend the Monday morning's manager's meeting. Anyway, I will post it here anyway, since no monks have shown you a search and replace example yet. :-)
    use strict; my $string = '+5^7'; my $line = '((1+2)-4)*(2+5^7)'; # insert \ in front of pattern $line =~ s/(\Q$string\E)/\\$1/; print "$line\n";
    Basically you use \Q and \E to quote meta characters, or use the 'quotemeta' function.

    And the output is -
    ((1+2)-4)*(2\+5^7)
Re: Quoting metacharacters in regexen
by Anonymous Monk on Nov 24, 2003 at 00:09 UTC

    Either using quotemeta or "\Q \E" solves your problem.

    $_ = "+5^7"; $pattern = "+5^7"; print "ok\n" if m/\Q$pattern\E/;' $_ = "+5^7"; $pattern = quotemeta "+5^7"; print "ok\n" if m/$pattern/;'
Re: Quoting metacharacters in regexen
by evilsizord (Initiate) on Nov 24, 2003 at 00:58 UTC
    ahah thanks guys. i found out that the \Q didn't work the first time because i also used it in an s// function, and when i only did the left side, i.e. :

     s/\Q$string1\E/$string2/

    it works! I guess s// doesn't try to evaluate the replacement string as a regular expression after it interpolates it.
Re: Quoting metacharacters in regexen
by jZed (Prior) on Nov 24, 2003 at 00:06 UTC
    perldoc -f quotemeta