http://www.perlmonks.org?node_id=83923

Inspired by neophyte's question in the chatter about parsing a list of numerical data for the nearest value to a given (number) value, I tee off timidly and prepare for an ass-whoopin'.

Rules
1. sub must take 2 params:
1) list (or listref) of _numerical_ data (minimum 1 element)
2) a number - int/real/negative - whatever! as the "match-closest-to-this" number
not necessarily in that order.
2. the original order of the data must be maintained - you can't sort the data directly.
3. can't think of any more!

Update: 19:45 29/05/2001 (GMT)
Apologies if I did not make this clear: 2 things go into the sub - a number and a list. the order in which you pass these is up to you. the list can either go in as a strtaight list or as a reference to a list - your choice - just so long as the original isn't modified. and the return value from the sub should be either the value closest to the given number or the index in the original list.

e.g.

```sub g {blah}

print "Closest value is ",g(@list,\$number);
# or
print "Closest value is ",g(\$number,@list);
# or
print "Closest value is ",g(\@list,\$number);
# or
print "Closest value is ",g(\$number,\@list);
# OR
print "Closest value is ",\$list[g(@list,\$number)];
# or
print "Closest value is ",\$list[g(\$number,@list)];
# or
print "Closest value is ",\$list[g(\@list,\$number)];
# or
print "Closest value is ",\$list[g(\$number,\@list)];

```#!perl -w
use strict;

chomp(my @list = <DATA>);

# FORE!!! 78 chars.
sub g {my%h=();my\$n=pop;\$h{abs(\$_-\$n)}=\$_ for@_;my@s=sort{\$a<=>\$b}keys
+%h;\$h{shift@s};}

print g(@list,10);

__DATA__
17
1.4
18.2
7.9
12.2
12.5
1.1
7.8
18.3
20
6.7
6.9
18.1
1.5
17.7
16.6
1.2
1.3
17.5