#################################################################### ## MAIN #################################################################### my @array = (1, 4, 4, 65, 100, 102); my $closest_element = @{closest_element(\@array)}[0]; print "The closest element to the element $element in the array (@array) is the element $closest_element\n"; #################################################################### ## SUBS #################################################################### sub closest_element { #to execute a binary search on the closest element of an input array my ($array) = @_; my $end = @$array; my $not_middle = int(($end-1) / 2); #compute $not_middle my $try = @$array[$not_middle]; #try an element return $try <= $element ? #return the closest element after having checked the below statements (abs($try-$element)= @$array[$not_middle-1] ? [@$array[$not_middle-1]] : closest_element([@$array[0 .. $not_middle]])); }