> From: Edward M. Perry [mailto:eperry@learjet.com] > Sent: Friday, July 16, 1999 11:00 > To: fwp@technofile.org > Subject: [FWP] Closest hash value > > Here is the problem: given a key ($key), and a hash (%h), I want the value > of the closest hash key. I came up with this which is only moderately fun. > Really it works pretty well, assuming keys are numeric and the hash is > small. Mapping to %temp is weak. > > An array seems unreasonable because in reality the keys (or indicies) are > large and the array would be very sparse. > > $key = 5; > %h = (1=>'one', 2=>'two', 4=>'four', 8=>'eight'); > > %temp = map { abs($_-$key) => $_ } keys %h; > $val = $h{$temp{(sort({$a<=>$b} keys %temp))[0]}}; > > Any ideas? my $key = 5; my %h = (1=>'one', 2=>'two', 4=>'four', 8=>'eight'); my ($min, $val) = ~0; $min > abs($_ - $key) and $min = abs(($val = $_) - $key) for keys %h; print $h{$val}; __END__ This is much less fun than your solution. -- Larry Rosler Hewlett-Packard Laboratories http://www.hpl.hp.com/personal/Larry_Rosler/ lr@hpl.hp.com ==== Want to unsubscribe from Fun With Perl? Well, if you insist... ==== Send email to <fwp-request@technofile.org> with message _body_ ==== unsubscribe