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

is it possible to use a scalar variable in a regex? As in:
$date = "dec"; @months_we_ski = ("nov", "dec"); foreach $month (@months_we_ski) { if ($month =~ /$date/) { print "yep, we ski in $month\n"; } }
Of course this doesn't work:) but is there something that makes it work? Thanks for any enlightenment, Mike

Replies are listed 'Best First'.
Re: regex variables
by btrott (Parson) on Sep 01, 2000 at 03:24 UTC
    It does so work! :) Did you try it? Result:
    yep, we ski in dec
    A few tips, then:
    • If you'll be matching against the same variable (like $date) multiple times, use the /o operator. That way Perl will only compile the regex once, not each time through the loop.
    • You could also compile such a regex using the qr operator. Check that out, as well.
    • Of course, in this case, you might want to just use eq. :)
    If I misunderstood what you're asking, let me know.
(bbq) RE: regex variables
by BBQ (Deacon) on Sep 01, 2000 at 18:33 UTC
    I'm not sure I understand the question, and as btrott already said you probably might have wanted to use eq instead. Anyway...
    # this works my $date = 'dec'; foreach ('november', 'december') { print "yeah, we ski in $_\n" if /$date/; } # this doesn't my $date = 'december'; foreach ('nov', 'dec') { print "yeah, we ski in $_\n" if /$date/; }

    # Trust no1!