NAME
Attribute::Generator - Python like generator powered by Coro
SYNOPSIS
use Attribute::Generator;
sub fizzbuzz :Generator {
my($i, $end) = @_;
do {
yield (($i % 3 ? '':'Fizz').($i % 5 ? '':'Buzz') || $i)
} while $i++ < $end;
}
my $generator = fizzbuzz(1, 100);
while(defined (my $val = $generator->next())) {
print "$val\n";
}
while(<$generator>) {
print "$_\n";
}
DESCRIPTION
Attribute::Generator realizes Python like generators using the power of Coro module. This module provides :Generator
CODE attribute which declares generator subroutines, and exports yield
function which is like yield
in Python.
FUNCTIONS
- :Generator attribute
-
This CODE attribute declares generator. When generator subroutines are called, it returns an iterator object that has next() method.
- $generator->next()
-
Advances generator until next yield called.
- $generator->send(EXPR)
-
Send a value to the generator. In generator subroutine, sent value can be received as return value of yield(): e.g.
sub foo:Generator { my $i = 0; while() { if(defined yield $i++) { $i=0; } } }
This generator, yields 0, 1, 2, 3.. , can be reset by calling $gen->send(1).
Returns the generator itself.
Note: Unlike Python, send() does *NOT* advances iterator.
- yield EXPR
-
When you call yield in generator, current status of the generator are frozen and EXPR is returned to the caller of $generator->next().
Note that calling yield() outside of :Generator subroutines are strictly prohibited.
AUTHOR
Rintaro Ishizaki <rintaro@cpan.org>
SEE ALSO
LICENSE
This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself.