So, if I understand coroutines correctly, what about the following idea?
- Create a function named &yield and export it into the caller's namespace.
- When the module exporting the &yield is used, it uses B::Deparse to make the calling code easier to parse and then insert unique labels with naked blocks before every &yield.
- When &yield is called, it uses PadWalker to save the state of the scratchpad and toggles a bit saying that "I've been called", and then returns from the sub using something like rreturn from Want.
- At the top of every sub, insert a bit of code that goes to the label in front of the last &yield called in that function.
- The &yield is executed, sees the bit that says "I saved the state last time", so it instead uses PadWalker to restore the state.
Am I missing anything here? This implementation seems a lot simpler (and closer to Perl6 syntax) then the Coro bundle on the CPAN.
As far as I can tell, this would still be a rather limited implementation and might not work with closures. However, it seems so obvious that I know I have to be missing something...
Join the Perlmonks Setiathome Group or just click on the the link and check out our stats.