Others have mentioned binary search in case your array is sorted. If your array is not sorted, you'll have to scan over the whole thing. Here's a short way to do this that makes the intent obvious:
use List::Util 'max'; my $selected = max grep { $find >= $_ } @array;
That's somewhat inefficient, however, because it actually loops twice (once for the grep and again over whatever grep produces).
You could write it in one loop this way:
# Find the largest number in @array # that is <= $find and put it in $selected my $selected; foreach my $number ( @array ) { $selected = $number if $find >= $number and $number > $selected; last if defined $selected and $selected == $find; }
If you're not going to have a huge list, there's little downside to doing it the easy way. (In fact, for short lists, I wouldn't be surprised if the grep method is faster.) If you do decide to write your own loop, be sure to comment it, and maybe put it off in a sub with a good name.
In reply to Re: find closest element of array without going over
by kyle
in thread find closest element of array without going over
by sadfaceman
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |