Skip to content

Instantly share code, notes, and snippets.

@mwgamera
Last active December 14, 2015 16:19
Show Gist options
  • Save mwgamera/5114294 to your computer and use it in GitHub Desktop.
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).
#!/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