Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw
 
PerlMonks  

Re: Comparing against multiple values

by PrimeLord (Pilgrim)
on Mar 18, 2002 at 19:19 UTC ( [id://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
Domain Nodelet?
Node Status?
node history
Node Type: note [id://152563]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others romping around the Monastery: (1)
As of 2024-04-25 19:43 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found