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
In reply to Re: Improve my lookup script
by Athanasius
in thread Improve my lookup script
by jjap
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |