"Martin, James S." wrote:
> 
> I have an array say:
> 
> @numbers =qw(100 125 150 200 300 325);
> 
> and have a string, say
> 
> $value = 120;
> 
> What I would like to do, is return the number from @numbers that is closest
> to $value.. In this case it would be 120.  How do I do this?

Assuming [a] by string you mean number; and [b] closest can be greater
and/or lesser, try this:

#! perl -w
use strict;
my @nums = qw(100 125 150 200 300 325 115);
my $value = 120;
my @tmp;
for (@nums) {
        my $abs = abs($value - $_);
        @tmp = ( $abs, $_ ), next unless @tmp;
        push @tmp, $_ if $abs == $tmp[0];
        @tmp = ( $abs, $_ ) if $abs < $tmp[0];
}
print "\n\t*Closest* to $value: ", join ' ', @tmp[1..@tmp], "\n";
exit 0;

-- 

Best Regards,

mds
mds resource
888.250.3987

"Dare to fix things before they break . . . "

"Our capacity for understanding is inversely proportional to how much we
think we know.  The more I know, the more I know I don't know . . . "
_______________________________________________
Perl-Win32-Users mailing list
[EMAIL PROTECTED]
http://listserv.ActiveState.com/mailman/listinfo/perl-win32-users

Reply via email to