On Fri, Jul 16, 1999 at 01:00:21PM -0500, Edward M. Perry wrote: > > 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? > You don't need %temp; just sort directly. $val = (sort {abs($a - $key) <=> abs($b - $key)} keys %h)[0]; Of course, you could use an Orcish Maneuver or a Schwartzian Transform for the sort if you wanted. Ronald ==== Want to unsubscribe from Fun With Perl? Well, if you insist... ==== Send email to <fwp-request@technofile.org> with message _body_ ==== unsubscribe