in reply to Find a number in a list closest to a target

Just because &reduce is pretty and TMTOWTDI:

use List::Util 'reduce'; my $closest = reduce { abs($a - $ctime) < abs($b - $ctime) ? $a : $b + } @epochs; print $closest;

or even

my $closest = reduce { $a->[1] < $b->[1] ? $a : $b } map [ $_ => abs($ctime - $_) ], @epochs; print $closest->[0];

Not that I'd expect the second to be more efficient in this particular case. :-) (In fact, I benchmarked the regular for loops in the previous replies with and without a temporary $diff variable and it seemed like it was more efficient to just redo the math (on ActivePerl 5.8.0 build 806). But please verify that yourself, as the benchmark was hasty and inexhaustive.)

ihb