in reply to constants within regular expression?

Constants aren't interpolated as such inside quotes or regexp quote-like m// expressions. Inside the m// expression, the text that you're using as the name of a constant is actually just seen as literal text to match.

This is documented in the POD for the 'constant' pragma:

Constants defined using this module cannot be interpolated into strings like variables.

You can work around that behavior like this:

use constant MYTEST => '.txt'; my $expression = quotemeta( MYTEST ); my $string = "test.txt"; if ( $string =~ /$expression/ ) { print "Match\n"; }


Dave


"If I had my life to live over again, I'd be a plumber." -- Albert Einstein

Replies are listed 'Best First'.
Re: Re: constants within regular expression?
by Zed_Lopez (Chaplain) on Nov 26, 2003 at 06:34 UTC

    Another WTDI:

    print "Match" if $string =~ /@{[MYTEST]}/;
      @{[MYTEST]} leaves out the all-important "quotemeta". In the OP's example, the literal text to match against was ".txt", and without quotemeta, '.' will match anything, instead of dot.


      Dave


      "If I had my life to live over again, I'd be a plumber." -- Albert Einstein

        Ah, didn't even think about using ref/deref to do so. In that case, to match correctly:

        /\Q@{[EXTENSION]}\E\z/

        @{[MYTEST]} leaves out the all-important "quotemeta".

        Well, to be fair, whether or not it is all important depends entirely on the behavior you want. Granted, the OP, probably did not want the dot in ".txt" to match anything; so he'd probably want to do it like /\Q@{[EXTENSION]}/ instead. But, someone else might want to use a constant like use constant FILEPATTERN => 'foo.*\.txt'; in which case he probably wouldn't want to quote his metacharacters.

        -sauoq
        "My two cents aren't worth a dime.";
        
      Thanks folks! This gives me a number of different ways to solve the problem.