I implemented a simple iterator in perl. I usually work with C # and often use iterators and functional programming. So I thought it would be easy to get some basics working in perl.
The problem is that I am getting some bad performance, I do not expect it to be faster than for foreach, but I thought that someone could give me some idea on how to speed it up.
Here is the courage of my package:
package Iterator;
use strict;
sub new {
my $type = $_[0];
my $this = {};
$this->{Array} = @_[1];
$this->{Index} = 0;
$this->{Sub} = sub {
my @array = @{$this->{Array}};
return $#array >= $this->{Index} ? $array[$this->{Index}++] : undef;
};
bless($this, $type);
return $this;
}
sub Next {
return $_[0]->{Sub}->();
}
Lets do this:
my $iterator = Iterator->new(\@array);
while (defined(my $current = $iterator->Next())) {
print $current, "\n";
}
Not screaming ... bye.
Also allows you to use some functional code:
my $sum = 0;
Iterator
->new(\@array)
->Where(sub { $_[0] % 2 == 0 })
->ForEach(sub { $sum += $_[0] });
To sum all the even values ββof the array.
My bottleneck is the iteration code:
$this->{Sub} = sub {
my @array = @{$this->{Array}};
return $#array >= $this->{Index} ? $array[$this->{Index}++] : undef;
};
Any pointers to speed this up?