The following is pure Perl implementation of the semi-coroutine language construct (a.k.a. asymmetric coroutine or Python generator).

EulerMB::Coroutine - http://www.math2.org/eulermb/pod/EulerMB/Coroutine.html

==========
SYNOPSIS

use EulerMB::Coroutine qw(:all);

sub gen_func
{
    my $x = 0;
    return coroutine {
        COBEGIN();
        while($x < 10) {
            YIELD($x);
            $x++;
        }
    }->wrap();
}

my $func = &gen_func();
while(my @x = $func->()) {
    print "$x[0]\n";
}
# prints 0..9
==========

It is inspired by the Coro distribution (http://search.cpan.org/~mlehmann/Coro), particularly Coro::Cont (BTW, is the use of the term "continuation" correct in that module?), as well as coroutines in other languages (e.g. Lua). I wrote this specifically for another lexing/parsing module:

  http://www.math2.org/eulermb/pod/EulerMB/Content.html

and it did the job for that application. You may refer to it for examples. I had reasonable success using Coro instead, but I found it segfaulted if I wasn't careful, it had some problems with threading-enabled Perl, and I didn't want my module dependent upon something that might make deployment more difficult.

My question is whether it is worth renaming this EulerMB::Coroutine module to something more generic and putting it onto CPAN. Also, I'm open to any ideas to making it better. It relies on a bit of source filtering, which some people don't like, but the source filtering is fairly tame, and I don't know of any better way to do coroutines reliably and conveniently in Perl without modifying Perl itself. There is also a number of "Limitations and Caveats" as given in the POD. Some type of symmetric coroutine might in implemented in a similar manner as well.

best regards,
-david manura, dm.list[-at-]math2.org



Reply via email to