in reply to Improve my lookup script

Hello jjap,

There is nothing wrong with your approach, but here is an alternative which uses no modules:

#! perl use strict; use warnings; @ARGV == 1 or die "\nUsage: perl lookupArray.pl <integer>\n"; my $lookup = $ARGV[0]; my @array = sort { $a <=> $b } (67, 40, 11, 23, 52); my $prev = ( grep { $_ <= $lookup } @array )[-1]; my $next = ( grep { $_ >= $lookup } @array )[ 0]; printf "\nValue %d is %s\n", $lookup, ($prev && $next) ? "between $prev and $next" : $prev ? "above $prev" : "below $next";

Thanks to GlitchMr for the hint about getting min and max via array indices [0] and [-1]. I’ve really just taken this idea to its logical conclusion.

I make no claims for the efficiency of this approach, but it does have the advantages of compactness and (I think) of clarity, as well as some minimum sanity checking.

Maybe looking at the task from this different angle will be useful for you? Hope it helps.

Update: Fixed sort as per Re^2: Improve my lookup script by ++GlitchMr, below.

Athanasius <°(((><contra mundum

Replies are listed 'Best First'.
Re^2: Improve my lookup script
by GlitchMr (Sexton) on Aug 22, 2012 at 16:14 UTC

    Just a small note, sort is lexical sort. While it doesn't matter in this case (every number has this same length), you probably meant sort { $a <=> $b }.

Re^2: Improve my lookup script
by jjap (Monk) on Aug 22, 2012 at 17:52 UTC
    Very neat approach! Of both grep and conditional operator. Many thanks!