Rintaro Ishizaki


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 attribute

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++) {

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.


Rintaro Ishizaki <rintaro@cpan.org>




This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself.