jjap has asked for the wisdom of the Perl Monks concerning the following question:
Dear Monks,
I made this script to find where a value is along an array. This code is pretty explicit and works as expected, but I am looking for advice on improving its efficiency or elegance before implementing it further.
Thanks and best regardsuse strict; use warnings; use List::Util qw(max min); my @array = (11, 23, 40, 52, 67); my ($minarray, $maxarray); my $lookup = $ARGV[0]; my ($prev, $curr); $minarray = min(@array); $maxarray = max(@array); foreach my $i (@array){ if ($lookup < $minarray or $lookup > $maxarray){ print "$lookup is out of bounds\n"; last; } if ($i == $lookup) { print "Exact match $i\n"; last; } unless ($prev) { $prev = $i; next; } if ($i < $lookup) { $prev = $i; next; } else { $curr = $i; } if ($curr > $lookup) { print "Value $lookup, is between $prev and $curr\n"; last; } } # >perl lookupArray.pl 27 # Value 27, is between 23 and 40
Update: Minor edit to correct as per BillKSmith's observation.
And many thanks to all for the nice variants and improvements offered. Cheers!
|
---|
Replies are listed 'Best First'. | |
---|---|
Re: Improve my lookup script
by GlitchMr (Sexton) on Aug 22, 2012 at 15:14 UTC | |
by jjap (Monk) on Aug 22, 2012 at 15:46 UTC | |
Re: Improve my lookup script
by Athanasius (Archbishop) on Aug 22, 2012 at 16:07 UTC | |
by GlitchMr (Sexton) on Aug 22, 2012 at 16:14 UTC | |
by jjap (Monk) on Aug 22, 2012 at 17:52 UTC | |
Re: Improve my lookup script
by Kenosis (Priest) on Aug 22, 2012 at 18:35 UTC | |
Re: Improve my lookup script
by BillKSmith (Monsignor) on Aug 22, 2012 at 20:05 UTC |
Back to
Seekers of Perl Wisdom