Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things
 
PerlMonks  

Re: speeding up a hash lookup

by arturo (Vicar)
on Mar 27, 2001 at 20:50 UTC ( [id://67534]=note: print w/replies, xml ) Need Help??


in reply to speeding up a hash lookup

I'm not sure it would be faster, but you can use the nifty grep operator in conjunction with the keys function to achieve similar effects:

sub getIntensity { my $target = shift; # => $_[0], idiomatic my $tol = .3; my @matching_keys = grep { abs($target-$_) <= $tol } keys %massint; my $intensity = 0; foreach (@matching_keys) { $intensity = $massint{$_} > $intensity ? $massint{$_} : $intensity; } $intensity; }

First, you grab the keys within the tolerance range, and then you go through them to nab the greatest value (the ternary operator EXPR ? EXPR1 : EXPR2 returns EXPR1 if EXPR is true, and EXPR2 otherwise). You could, of course, do away with @matching_keys and run the foreach over the grep statement, but that doesn't illustrate the technique as clearly.

HTH

Philosophy can be made out of anything. Or less -- Jerry A. Fodor

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others musing on the Monastery: (3)
As of 2024-04-19 17:05 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found