Bob Showalter wrote:
> Mike Blezien wrote:
>> Hello,
>> 
>> is it possible, with perl, to find the closest numerical value to a
>> set value. IE. a set value of 15 and I have five values,
>> 208,258,56,123 
>> 
>> is there a function too go through the five values array to find the
>> closest to 15 ??
> 
> Here's an approach that doesn't use sorting:
> 
>   #!/usr/bin/perl
> 
>   print "closest=", closest(15, 208, 258, 56, 123), "\n";
> 
>   sub closest {
>       my $find = shift;
>       my $closest = shift;
>       abs($_ - $find) < abs($closest - $find) and $closest = $_ for
>       @_; $closest;
>   }

And in a more readable fashion:

sub closest
{
        my $find = shift;
        my $closest = shift;
        for my $num (@_)
        {
                if (abs($num - $find) < abs($closest - $find))
                {
                        $closest = $num;
                }
        }
        return $closest;
}

--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
<http://learn.perl.org/> <http://learn.perl.org/first-response>


Reply via email to