in reply to constants within regular expression?

Constants are transformed into subroutines (at least in some cases, I'm not too familiar with them at all). So one possibility of what to do is get a subroutine call inside your regex. Looking at the perldocs for constant and perlre, I came up with this working code. It uses a highly experimental regex feature, so you probably won't want to use this. Take a look at the perlre documentation to learn more about what the (??{}) construct does. It worked for me, so here it is.

#!/usr/bin/perl -w $|++; use strict; use constant EXTENSION => '.txt'; my $file = shift; die sprintf( 'cannot match "%s" extension in "%s"', EXTENSION, $file ) unless $file =~ /(??{EXTENSION()})\z/;

Update: I figure I'd cross this out just because you really don't want to use an experimental feature, do you? As discovered with the help of Zed_Lopez, you should really use something like this regex snippet. Or, follow perrin's advice and just use variables instead of constants :)

Replies are listed 'Best First'.
Re: Re: constants within regular expression?
by sauoq (Abbot) on Nov 26, 2003 at 06:49 UTC
    Constants are transformed into subroutines (at least in some cases, I'm not too familiar with them at all).

    Constants created with constant.pm are indeed subs (in all cases.) They are made by aliasing the constant's name to an anonymous sub with an empty prototype the body of which is simply the supplied value. The empty prototype is a hint to perl that the sub is a candidate for inlining. In other words, you could create your own "constants" with code like

    sub MY_CONSTANT () { 42 }
    if you wanted.

    -sauoq
    "My two cents aren't worth a dime.";
    

      i don't know what the empty prototype implies for inlining, but it also keeps the sub from swallowing arguments.

      sub A () {1}; sub B {2}; print A + 1,$/; print B + 1,$/; __END__ prompt$ perl test.pl 2 2prompt$

      without the empty prototype subs wouldn't work very well for constants.

        i don't know what the empty prototype implies for inlining

        Read this and you will (from perldoc perlsub):

        Constant Functions Functions with a prototype of "()" are potential candidates for inlin- ing. If the result after optimization and constant folding is either +a constant or a lexically-scoped scalar which has no other references, then it will be used in place of function calls made without "&". Calls made using "&" are never inlined. (See constant.pm for an easy way to declare most constants.)

Re: Re: constants within regular expression?
by ysth (Canon) on Nov 27, 2003 at 21:54 UTC