Beefy Boxes and Bandwidth Generously Provided by pair Networks
The stupid question is the question not asked
 
PerlMonks  

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/; }


    #!/home/bbq/bin/perl
    # Trust no1!

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others chanting in the Monastery: (3)
As of 2021-12-08 22:52 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    R or B?



    Results (36 votes). Check out past polls.

    Notices?