Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask
 
PerlMonks  

Re: Comparing against multiple values

by PrimeLord (Pilgrim)
on Mar 18, 2002 at 19:19 UTC ( #152563=note: print w/replies, xml ) Need Help??


in reply to Comparing against multiple values

I am not sure if it would be faster or not, but you could always store each of the match terms as keys in a hash and do something like this.

my %hash = qw( $bar => 1 $baz => 1 $boo => 1 ); print "yep!\n" if exists $hash{$foo};


HTH

-Prime

Update: I tested the code and it is considerably faster. The first benchmark time is the regex solution and the second benchmark time is using a hash. Both tests were run 100,000 times.

Regex Solution timethis 100000: 18 wallclock secs ( 0.41 usr + 0.05 sys = 0.45 CPU) Hash Solution timethis 100000: 1 wallclock secs ( 1.58 usr + 0.00 sys = 1.58 CPU)

Replies are listed 'Best First'.
Re^2: Comparing against multiple values
by tadman (Prior) on Mar 18, 2002 at 19:30 UTC
    Maybe you want to score points for obfuscation:
    if ({map{$_=>1}($bar,$baz,$boo)}->{$foo}) { print "Yes!\n"; }
    A dirty, and almost as quick way is:
    if (grep{$_ eq $foo} $bar, $baz, $boo) # ...
    If you are comparing frequently, you might want to have a persistent hash which you can refer to on a regular basis. Why create it every time if it is the same?

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://152563]
help
Chatterbox?
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others chanting in the Monastery: (3)
As of 2018-07-22 09:20 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    It has been suggested to rename Perl 6 in order to boost its marketing potential. Which name would you prefer?















    Results (453 votes). Check out past polls.

    Notices?