Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the most elegant way in Perl to expand an iterator into a list?

Tags:

perl

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?

like image 463
Mithaldu Avatar asked Oct 10 '10 18:10

Mithaldu


People also ask

What are the Iterables in Python?

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.

What is next ITER in Python?

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.


2 Answers

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
like image 79
daxim Avatar answered Oct 13 '22 00:10

daxim


It entirely depends on the iterator implementation. If next_hsp is the only available method, then you're doing it right.

like image 33
Pedro Silva Avatar answered Oct 13 '22 02:10

Pedro Silva