----- Original Message -----
From: "Mike Blezien" <[EMAIL PROTECTED]>
Newsgroups: perl.beginners
To: "Perl List" <[EMAIL PROTECTED]>
Sent: Sunday, May 16, 2004 12:50 PM
Subject: Find closest value
> 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 ??
Hi Mike
Doing a quick search on CPAN didn't turn up anything, (as far as I can
tell),
but the following code will do what you want, I believe, but is not a
function.
Chris
#!/usr/bin/perl
use strict;
use warnings;
my $set = 15;
my @vals = (208,258,56,123);
my ($min_idx) = map{$_->[0]}
sort{ $a->[1] <=> $b->[1]}
map{[$_, abs($vals[$_]-$set)]} 0..$#vals;
print "index of element closest to $set is $min_idx",
" with value $vals[$min_idx]\n";
__END__
*** Output ***
index of element closest to 15 is 2 with value 56
--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
<http://learn.perl.org/> <http://learn.perl.org/first-response>