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

Re: Dynamic regexp from array values

by jdporter (Paladin)
on Feb 11, 2003 at 18:01 UTC ( [id://234479]=note: print w/replies, xml ) Need Help??


in reply to Dynamic regexp from array values

Regexes are just strings (well, at least you can think of them that way), which means you can build them up just as you would any other strings.
my $regex = join '|', @all_the_different_values; if ( $data =~ /$regex/ ) . . .
If you need only exact matches, then you should probably write it as
if ( $data =~ /^($regex)$/ ) . . .
On the other hand, unless you're using the power of regexes to do something like "wildcard" matching, there's another way to do it you should consider: Make a "set" of the values, and test for the existence of $data in that set.
my %set; @set{ @all_the_different_values } = (); # make the set if ( exists $set{ $data } ) . . .

jdporter
The 6th Rule of Perl Club is -- There is no Rule #6.

Replies are listed 'Best First'.
Re (2): Dynamic regexp from array values
by VSarkiss (Monsignor) on Feb 11, 2003 at 18:16 UTC

    jdporter makes a very good point above. I just want to make it explicit because it's a fairly common over-generalization: If you're only testing for string equality, don't use regular expressions at all. I can't tell from your note whether that's the case or not, but if so, a regular expression is much more work than necessary.

    In that case, using a hash as shown above will work, and will be faster, though it may consume more memory. Another alternative is to use a simple loop:

    foreach (@target_strings) { if ($data eq $_) { doSomething(); last; } }
    (I'm guessing that you can short-circuit the loop if any one of the targets matches.)

Re: Re: Dynamic regexp from array values
by tachyon (Chancellor) on Feb 11, 2003 at 18:59 UTC

    You *must* use quotemeta or \Q \E if you are going to do this and qr// or a /o modifier on the regex is also not a bad idea:

    my $re = join '|', map{quotemeta}@vals; $re = qr/$re/; if ( $var =~ m/$re/ ) { blah }

    If you fail to quotemeta then your regex will either die or commit weirdness if there are any / ( ) { } ^ $ * ? + \ - . chars present in @vals. quotemeta is a vital part of doing this.

    cheers

    tachyon

    s&&rsenoyhcatreve&&&s&n.+t&"$'$`$\"$\&"&ee&&y&srve&&d&&print

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (6)
As of 2024-04-23 12:55 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found