[Date Prev][Date Next][Thread Prev][Thread Next] [Search] [Date Index] [Thread Index]

RE: [FWP] Closest hash value



> 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

I knew I was making it more fun than it should be.
Your straight forward approach has the added bonus
of being able to decide if 'ties' should resolve to
the lower or upper key. Thanks.

==== Want to unsubscribe from Fun With Perl?  Well, if you insist...
==== Send email to <fwp-request@technofile.org> with message _body_
====   unsubscribe