Created
July 8, 2013 22:02
-
-
Save jberger/5952868 to your computer and use it in GitHub Desktop.
Yet another Python-like generator using Coro
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env perl | |
use v5.10; | |
use strict; | |
use warnings; | |
package MyGenerator; | |
use Coro; | |
sub new { | |
my $class = shift; | |
my $sub = shift; | |
return bless { sub => $sub }, $class; | |
} | |
sub next { | |
my $self = shift; | |
$self->{coro} = async { | |
local $_ = $self; | |
$self->{sub}->(); | |
} unless $self->{coro}; | |
cede; | |
return $self->{retval}; | |
} | |
sub yield { | |
my $self = shift; | |
$self->{retval} = shift; | |
cede; | |
} | |
package main; | |
sub generator (&) { | |
my $sub = shift; | |
my $gen = MyGenerator->new($sub); | |
return $gen; | |
} | |
my $gen = generator { | |
my $x = 0; | |
while (1) { | |
$x += 2; | |
$_->yield($x); | |
} | |
}; | |
say $gen->next; | |
say $gen->next; | |
say $gen->next; | |
say $gen->next; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment