Mike Blezien wrote:
>
> 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 ??

Hi Mike.

There's no built-in function, but it's simple to write one; the code below will
do what you want. It's not particularly efficient, but is more than likely
to be fast enough for you unless your list of values is huge.

HTH,

Rob


use strict;
use warnings;

my $set = 15;
my @vals = (208, 258, 56, 123);

print closest($set, @vals), "\n";

sub closest {
  my $val = shift;
  my @list = sort { abs($a - $val) <=> abs($b - $val) } @_;
  $list[0];
}

**OUTPUT

56



-- 
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