in reply to Regex help

quotemeta

Replies are listed 'Best First'.
Re^2: Regex help
by moritz (Cardinal) on May 06, 2009 at 11:23 UTC
    ... or /\Q$variable\E/ (which uses quotemeta under the hood)
      What is the reason to put \E at the end of a regexp?
        It doesn't make a difference, but if you want to write something after the variable, it's treated literally unless there's an \E. That's a common mistake I made, so I always haven an \E for every \Q.

        Example:

        $ perl -Mre=debug -e 'my $x= "*"; /\Q$x.+/' Compiling REx "\*\.\+" Final program: 1: EXACT <*.+> (3) 3: END (0) anchored "*.+" at 0 (checking anchored isall) minlen 3 Freeing REx: "\*\.\+"
        You see that the .+ is also treated literally.
        It's easier to say

        Use /\Q$variable\E/

        than

        Use /\Q$variable/ except if that's not the entire regexp pattern. You probably have to use /\Q$variable\E/ then.

Re^2: Regex help
by bingohighway (Acolyte) on May 06, 2009 at 12:19 UTC
    Is there a way of running quotemeta between bounds however, e.g.
    $line = 'if($appliance =~ /toilet(32)/)';
    Should be:
    $line = 'if($appliance =~ /toilet\(32\)/)';
    In a simple one-liner?

    Cheers!

Re^2: Regex help
by bingohighway (Acolyte) on May 06, 2009 at 11:51 UTC
    Superb :-) It's amazing the little jewels Perl has hidden away.