-----Original Message-----
From: Martin, James S. [mailto:[EMAIL PROTECTED]]

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?

James
------------------------------

All these replies seem complicated.
As noted by one replier, there is a question about whether your really mean
"have a string" or really "have a number" but since you show literal numbers
and talk about numbers, I'm gonna assume you mean numbers.

I think also that your @numbers probably should be assigned like this:

    @numbers = (100, 125, 150, 200, 300, 325);

hmmm - you also say "in this case it would be 120" but I cannot see that
value in your list. Do you mean 125? It must be very late at night out
there, or you've run out of coffee ;-) I'm going to assume also that your
target result is 125.

Try this:

my $closest;    # will be undef - primes the loop for the first pass or an
empty list
foreach (@numbers)
    { $closest = $_ if ! defined $closest or abs($_ - $value) < abs($closest
- $value) }
# If ! definer $closest then the @numbers array is empty

If your rule for closest is slightly more complicated (one replier
questioned whether you want the closest from above or below or something
like that) then you merely need to change the rule on the right-hand side of
the "or" operator.

__END__
Andrew Hamm
Technical Consultant
Sanderson Wacher Pty Ltd
e-mail: <mailto:[EMAIL PROTECTED]>
web:    <http://www.sanderson.net.au>
--
"Having fun is half the fun" - Guru Adrian
No matter what happens, somebody will find a way to take
it way too seriously - Micheal Tod (wishes he said this)
_______________________________________________
Perl-Win32-Users mailing list
[EMAIL PROTECTED]
http://listserv.ActiveState.com/mailman/listinfo/perl-win32-users

Reply via email to