From 1d5bc34e7ec877444a4ac6eee3cc408924731304 Mon Sep 17 00:00:00 2001 From: Andrew Yates <ayates@ebi.ac.uk> Date: Wed, 11 May 2011 16:28:16 +0000 Subject: [PATCH] Bringing in each() as a method on Iterator --- modules/Bio/EnsEMBL/Utils/Iterator.pm | 24 ++++++++++++++++++++++++ modules/t/iterator.t | 4 ++++ 2 files changed, 28 insertions(+) diff --git a/modules/Bio/EnsEMBL/Utils/Iterator.pm b/modules/Bio/EnsEMBL/Utils/Iterator.pm index dad22ee0ee..6a32f07008 100644 --- a/modules/Bio/EnsEMBL/Utils/Iterator.pm +++ b/modules/Bio/EnsEMBL/Utils/Iterator.pm @@ -249,6 +249,30 @@ sub map { }); } +=head2 each + + Example : $iterator->each(sub { print $_->name, "\n"; }); + Description: Performs a full iteration of the current iterator instance. + Argument : a coderef which returns the desired transformation of each element. + $_ will be set locally set to each element. + Returntype : None + Exceptions : thrown if the argument is not a coderef + Caller : general + Status : Experimental + +=cut + + +sub each { + my ($self, $coderef) = @_; + throw('Argument should be a coderef') unless ref $coderef eq 'CODE'; + while($self->has_next()) { + local $_ = $self->next(); + $coderef->($_); + } + return; +} + =head2 to_arrayref Example : my $arrayref = $iterator->to_arrayref; diff --git a/modules/t/iterator.t b/modules/t/iterator.t index a5d87a5433..36b1e56a11 100644 --- a/modules/t/iterator.t +++ b/modules/t/iterator.t @@ -123,5 +123,9 @@ $num = Bio::EnsEMBL::Utils::Iterator->new([1,2,3,4])->reduce(sub {$_[0] + $_[1]} is($num, 20, "reduce with initial value calculated sum correctly"); +$num = 0; +Bio::EnsEMBL::Utils::Iterator->new([1..12])->each(sub { $num++; }); +is($num, 12, 'each iterates over all elements'); + done_testing; -- GitLab