Beefy Boxes and Bandwidth Generously Provided by pair Networks
good chemistry is complicated,
and a little bit messy -LW
 
PerlMonks  

regex variables

by Miker (Scribe)
on Sep 01, 2000 at 03:16 UTC ( [id://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 (Curate) 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?Last hourOther CB clients
Other Users?
Others contemplating the Monastery: (2)
As of 2024-04-26 05:16 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found