Last active
December 14, 2015 16:19
-
-
Save mwgamera/5114294 to your computer and use it in GitHub Desktop.
Simple generators for Perl using Coro::Channel and closures (unlike Coro::Generator which manipulates the state explicitly).
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 strict; | |
sub gen(&) { | |
use Coro; | |
my $fun = shift; | |
my $arg = new Coro::Channel; | |
my $out = new Coro::Channel; | |
my $yield = sub(@) { | |
$out->put([@_]); | |
@_ = @{$arg->get}; | |
wantarray ? @_ : pop; | |
}; | |
async { | |
sub yield(@); | |
Coro::on_enter { | |
no strict 'refs'; | |
*{'yield'} = $yield; | |
}; | |
Coro::on_leave { | |
no strict 'refs'; | |
undef *{'yield'}; | |
}; | |
$fun->(@{$arg->get}); | |
$out->shutdown; | |
}; | |
sub(@) { | |
$arg->put([@_]); | |
@_ = @{$out->get or []}; | |
wantarray ? @_ : pop; | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment