I have an iterator with this interface: $hit->next_hsp
The current implementation to listify it is:
my @list;
while ( my $hsp = $hit->next_hsp ) {
push( @list, $hsp );
}
Now I'm thinking that there might be better ways to do this in less code. What do you say, stackers?
Iterable is an object which can be looped over or iterated over with the help of a for loop. Objects like lists, tuples, sets, dictionaries, strings, etc. are called iterables. In short and simpler terms, iterable is anything that you can loop over.
The next() function returns the next item in an iterator. You can add a default return value, to return if the iterable has reached to its end.
All iterators I've ever seen return undef
to signify that they are exhausted. Therefore you should write while (defined(my $hsp = $hit->next_hsp))
. The following example demonstrates the fault in the question which tests for truth (aborts at 1) instead of definedness (passes 'liftoff').
use 5.010;
my $hit = __PACKAGE__;
sub next_hsp {
state $i;
$i++;
return ['mumble', 4, 3, 2, 1, 0, 'liftoff']->[$i];
}
# insert snippet from question here
It entirely depends on the iterator implementation. If next_hsp
is the only available method, then you're doing it right.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With