C
cp
I have a list of ids from a database, and a value for the currently
selected value. I need the previous value (or the index of the previous
value) and the next value in the list.
The ids will not neccessarily be in sequence. The function is called
once, so the original list does not need to be preserved. The list is
arbitrarily long.
I.e., given a list: 1, 3, 5, 7, 9 and the currently selected id is
value is 5, I need 3 and 7.
I came up with the following, and I have 2 basic questions:
1) is this the best solution?
2) How would I add error checking? I need to abort if the value passed
in is not part of the list, and I only want to check that once, not on
every recursion.
use strict;
use warnings;
my @ids = qw( 1 3 5 7 9 );
# testing
for( qw(3 5 9 7 1) ) {
print join("\t", array_nav( $_, @ids )), "\n";
}
exit(0);
sub array_nav {
my ($val, @ids) = @_;
my $test = shift @ids;
return ( $ids[-1], $ids[0] ) if $test == $val;
push @ids, $test;
array_nav( $val, @ids);
}
selected value. I need the previous value (or the index of the previous
value) and the next value in the list.
The ids will not neccessarily be in sequence. The function is called
once, so the original list does not need to be preserved. The list is
arbitrarily long.
I.e., given a list: 1, 3, 5, 7, 9 and the currently selected id is
value is 5, I need 3 and 7.
I came up with the following, and I have 2 basic questions:
1) is this the best solution?
2) How would I add error checking? I need to abort if the value passed
in is not part of the list, and I only want to check that once, not on
every recursion.
use strict;
use warnings;
my @ids = qw( 1 3 5 7 9 );
# testing
for( qw(3 5 9 7 1) ) {
print join("\t", array_nav( $_, @ids )), "\n";
}
exit(0);
sub array_nav {
my ($val, @ids) = @_;
my $test = shift @ids;
return ( $ids[-1], $ids[0] ) if $test == $val;
push @ids, $test;
array_nav( $val, @ids);
}