Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight

regex variables

by Miker (Scribe)
on Sep 01, 2000 at 03:16 UTC ( #30659=perlquestion: print w/replies, xml ) Need Help??

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!

Log In?

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://30659]
Approved by root
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others studying the Monastery: (4)
As of 2023-02-06 12:32 GMT
Find Nodes?
    Voting Booth?
    I prefer not to run the latest version of Perl because:

    Results (34 votes). Check out past polls.