http://www.perlmonks.org?node_id=884172


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