Skip to content
Snippets Groups Projects
Commit 7618db9c authored by Matthieu Muffato's avatar Matthieu Muffato
Browse files

Remember that undef has been found to avoid calling the coderef again

This is useful when working with coderefs that defer to
`$sth->fetchrow_arrayref`, which throws an error if called again after
having returned undef (which signifies the end of the data stream)

```
DBD::mysql::st fetchrow_arrayref failed: fetch() without execute()
```
parent 5b751321
No related branches found
No related tags found
2 merge requests!457Patch to support longer assembly names in the mapping session table.,!430Add next-value buffering to Bio::EnsEMBL::Utils::Iterator
......@@ -155,9 +155,12 @@ sub new {
sub next {
my $self = shift;
$self->{next} = $self->{sub}->() unless defined $self->{next};
return delete $self->{next};
$self->{next} = $self->{sub}->() unless exists $self->{next};
if (defined $self->{next}) {
return delete $self->{next};
}
return;
}
=head2 has_next
......@@ -175,7 +178,7 @@ sub next {
sub has_next {
my $self = shift;
$self->{next} = $self->{sub}->() unless defined $self->{next};
$self->{next} = $self->{sub}->() unless exists $self->{next};
return defined $self->{next};
}
......@@ -196,7 +199,7 @@ sub has_next {
sub peek {
my $self = shift;
$self->{next} = $self->{sub}->() unless defined $self->{next};
$self->{next} = $self->{sub}->() unless exists $self->{next};
return $self->{next};
}
......
......@@ -33,6 +33,23 @@ $it = Bio::EnsEMBL::Utils::Iterator->new(sub {return 3});
is($it->next, 3, "got expected value from iterator created from coderef");
# check that the coderef is not called any more once it returns undef
my $call_counter = 0;
$it = Bio::EnsEMBL::Utils::Iterator->new(sub {
++$call_counter;
if ($call_counter == 1) {
return 1;
} else {
return undef;
}
});
is($it->next, 1, "got expected value from iterator created from coderef");
is($it->next, undef, "got undef from iterator created from coderef once exhausted");
is($it->next, undef, "got undef from iterator created from coderef once exhausted");
is($call_counter, 2, 'Returned undef without calling the coderef any further');
# from now on we create an iterator from an arrayref because it's simpler
$it = Bio::EnsEMBL::Utils::Iterator->new([1,2,3]);
......
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment