mzedeler has asked for the wisdom of the Perl Monks concerning the following question:
Hi fellow perl monks.
I have had a nasty surprise when I discovered that Iterator prefetches values when instantiated. This causes non-pure functions to behave very, very strange. E.g.:
use Iterator; my $i = 0; my $iterator = new Iterator(sub { return ++$i }); print "Before calling anything: $i\n"; print "First call yields: ", $iterator->value, "\n"; print "After first call: $i\n";
This SHOULD print:
Before calling anything: 0 First call yields: 1 After first call: 1
But it does in fact print this:
Before calling anything: 1 First call yields: 1 After first call: 2
It seems that the author of Iterator wants it to contain a buffer of one value, but I have a very hard time understanding why. Could someone please enlighten me?
Here is an even more degenerate example using chained iterators:
use Iterator; my $i = 0; sub get_a { return new Iterator(sub { print "a called\n"; return $i++ }); } sub get_b { my $a = get_a; return new Iterator(sub { print "b called\n"; return $a->value }); } print "Now I will get_b ($i):\n"; $b = get_b; print "Got b ($i)\n"; print "First value is ($i):\n"; print "b: ", $b->value, " ($i)\n";
This SHOULD print:
Now I will get_b (0): Got b (0) First value is (0): b called a called b: 0 (1)
But it prints this:
Now I will get_b (0): a called b called a called Got b (2) First value is (2): b called a called b: 0 (3)
The strange behavior can be explained off when you consider the prefetch buffer, but it is very hard to use in practise.
RT for the module contains two reports regarding this, (I posted one of them):
Please let me know if there is any reasonable explaination for this behaviour.
Regards,
Michael Zedeler (MADZ).
|
---|
Replies are listed 'Best First'. | |
---|---|
Re: Any thoughs on Iterator prefetching?
by Transient (Hermit) on Jun 25, 2009 at 14:07 UTC | |
by mzedeler (Pilgrim) on Jun 25, 2009 at 20:52 UTC | |
Re: Any thoughs on Iterator prefetching?
by pKai (Priest) on Jun 25, 2009 at 13:42 UTC |