Attribute::Generator - Python like generator powered by Coro
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"; }
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.
:Generator
yield
This CODE attribute declares generator. When generator subroutines are called, it returns an iterator object that has next() method.
Advances generator until next yield called.
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.
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.
Rintaro Ishizaki <rintaro@cpan.org>
Coro::State
This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
To install Attribute::Generator, copy and paste the appropriate command in to your terminal.
cpanm
cpanm Attribute::Generator
CPAN shell
perl -MCPAN -e shell install Attribute::Generator
For more information on module installation, please visit the detailed CPAN module installation guide.