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

Monks, I thought \Q and \E in regexes means no interpolation happens, like the equivalent of '' for strings. But I guess I was wrong about that as the following snippet shows. Or is there indeed some way to get \Q and \E to literal-match the dollar, as it literal-matches parenthesis and most other special characters? Thanks!
use strict; use warnings; use Test::More qw(no_plan); like('a',qr/a/); #passes like('(',qr/\Q(\E/); #passes -- \Q\E works for parenthesis and most sp +ecial characters like('asdf$',qr/\Qasdf$\E/); #no -- but not for the dollar sign like('asdf$',qr/\Qasdf\$\E/); #no like('asdf$',qr/asdf$/); #no like('asdf$',qr/\$/); #passes -- you have to backslash the dollar
UPDATE: Much obliged, monks. Cutting to the good part, it seems my question can best be answered with: use quotemeta, and compile the result with qr.
use strict; use warnings; use Test::More qw(no_plan); like('asdf$', quotemeta('asdf$')); #fails my $re = quotemeta('asdf$'); like('asdf$', qr/$re/); #passes like('asdf$', qr/@{[ quotemeta('asdf$') ]}/); #passes

Replies are listed 'Best First'.
Re: Can I use Q and E to regex match the dollar sign?
by borisz (Canon) on Aug 30, 2005 at 18:21 UTC
    from the docs perldoc perlre:

    You cannot include a literal "$" or "@" within a "\Q" sequence. An unescaped "$" or "@" interpolates the corresponding variable, while escaping will cause the literal string "\$" to be matched. You'll need to write something like "m/\Quser\E\@\Qhost/".

    Boris

      So, in other words, the OP would have to move the literal $ outside the \Q\E set, like this:

      like('asdf$',qr/\Qasdf\E\$/);

      The other option, of course, would be something like:

      ## matches a literal '[a-z]$[0-9]' using quoting like( '[a-z]$[0-9]', quotemeta('[a-z]$[0-9]') );
      (As ikegami pointed out above)

      <-radiant.matrix->
      Larry Wall is Yoda: there is no try{} (ok, except in Perl6; way to ruin a joke, Larry! ;P)
      The Code that can be seen is not the true Code
      "In any sufficiently large group of people, most are idiots" - Kaa's Law
Re: Can I use Q and E to regex match the dollar sign?
by ikegami (Patriarch) on Aug 30, 2005 at 18:37 UTC
    No, \Q...\E doesn't escape $ and @. You can use quotemeta instead:
    like('asdf$', quotemeta('asdf$'));

    If you absolutely need to compile the regexp before calling like (doubtful), here are some possible calling syntaxes:

    $re = quotemeta('asdf$'); like('asdf$', qr/$re/); -or- like('asdf$', qr/@{[ quotemeta('asdf$') ]}/); -or- like('asdf$', map { qr/$_/ } map quotemeta, 'asdf$');