Beefy Boxes and Bandwidth Generously Provided by pair Networks
Problems? Is your data what you think it is?
 
PerlMonks  

Re: Lookup closest hash key

by (anonymized user) (Curate)
on Jan 25, 2011 at 16:49 UTC ( #884172=note: print w/replies, xml ) Need Help??


in reply to Lookup closest hash key

Nah, the whole point of a hash is that it obviates coding the B-tree yourself
my %distances = ( 452 => 'London', 678 => 'Paris', 890 => 'Rome', ); print nearest( 672, \%distances ) . "\n"; sub nearest{ my ( $dist, $href ) = @_; my ( $answer ) = ( sort { abs( $a - $dist ) <=> abs( $b - $dist ) +} keys %$href ); return $href -> { $answer }; }
update: you could use the orcish manoeuvre to minimise sort iterations but something as simple as abs( x - y ) seems too cheap to be worth it.

One world, one people

Replies are listed 'Best First'.
Re^2: Lookup closest hash key
by Anonymous Monk on Oct 08, 2014 at 19:08 UTC
    Didn't you mean this, rather?
    sub nearest{ my ( $dist, $href ) = @_; my ( $answer ) = ( sort { abs( $a - $dist ) <=> abs( $b - $dist ) +} keys %$href )[0]; return $href -> { $answer }; }
    Otherwise this is a great trick, thanks!
      my ($answer) creates list context, so the [0] at the end is not needed: it is a list assignment, the first element on the left gets the first element on the right. With the index at the end, you can drop the parentheses on the left, as it is a scalar assignment:
      my $answer = ( sort { abs( $a - $dist ) <=> abs( $b - $dist ) } keys % +$href )[0];
      لսႽ ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (6)
As of 2021-01-19 15:50 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Notices?