In #pm's IRC tonight, Petruchio was looking for a way to use constants (defined via "use constant") in regex's. The no-frills way is to just assign a temporary variable with the constant value, but this leads to extra code. Here's a way to do it with no extra variables. Simply, you need to wrap it in the 'magic' code that forces any expression to be evaluated when it's used in a string (that is '@{[ expr ]}'), and then use the \Q and \E modifiers to tell perl to execute that part of the code before starting the regex.

Update: As MeowChow's pointed out to me, it's not necessary to \Q\E within the substitition part of s/// for this to work, as well as in m// strings as well; code snippet has been updated to reflect this. Mainly, if you do so, realize any special symbols ('.', '{', '}', etc) wil be quoted (eg '.' to '\.'), if you do include the \Q\E.

use constant TEST => 3; my $string = "123456"; $string =~ s/\Q@{[ TEST ]}\E/9/; print $string, "\n"; # 129456 $string =~ s/2/@{[ TEST ]}/; print $string, "\n"; # 139456

Replies are listed 'Best First'.
Re: Using constants inside regex
by MeowChow (Vicar) on Jul 02, 2001 at 07:20 UTC
    It's a bit cleaner with a scalar ref-deref:
    $string =~ s/\Q${\TEST}\E/9/;
       MeowChow                                   
                   s aamecha.s a..a\u$&owag.print
Re: Using constants inside regex
by BrentDax (Hermit) on Jul 07, 2001 at 01:16 UTC
    <ShamelessSelfPromotion>
    You could also use the Filter::Interpolate module I put into Code Catacombs:
    use Filter::Interpolate; use constant TEST => 3; my $string="123456"; $string =~ s/\Q$(TEST)\E/9/; print $string, "\n"; $string =~ s/2/$(TEST)/; print $string, "\n";
    </ShamelessSelfPromotion>

    It should also be pointed out that the @{[THING]} hack will work with subroutines too. It will also work in double-quoted strings and anywhere else interpolation happens.

    =cut
    --Brent Dax

    @HPAJ=split("", "rekcaH lreP rentonA tsuJ"); print reverse @HPAJ; #sucky but who cares?