my @array = (4, 1, 0, 9, 6, 7, 4, 0, 2); my $v = 5; print grep {abs($_-$v) == abs((sort {abs($a-$v) <=> abs($b-$v)} @array)[0]-$v)} @array;