Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things

comment on

( #3333=superdoc: print w/replies, xml ) Need Help??
Here's a version that approximates your desired usage without gotos or source filters, and it's not obfuscated, IMO. Each yield section gets its own sub, and they're all wrapped in a sub that sets up the variables for the coroutine scope.
use warnings; use strict; package Coroutine; sub prototype { my $class = shift; bless shift(), $class; } sub instance { my $self = shift; my @sections = $self->(@_); return sub { return () unless @sections; (shift @sections)->(@_); } } package main; my $coroutine = Coroutine->prototype( sub { my $foo = shift; my @bar = @_; ( sub { print "1st section:\n"; print " $_\n" for @bar; return $foo++; }, sub { print "2nd section:\n"; print " $foo\n"; return rand() > .5 ? 'weird' : ++$foo; }, sub { print "3rd section:\n"; print " The end is near - goodbye cruel "; return pop @bar; } ) } ); my $wacky = $coroutine->instance(42, 'hello', 'world'); print "returned($_)\n" while ($_ = $wacky->()); print "Resetting...\n"; $wacky = $coroutine->instance('another', 'time', 'through'); print "returned($_)\n" while ($_ = $wacky->()); __END__ 1st section: hello world returned(42) 2nd section: 43 returned(44) 3rd section: The end is near - goodbye cruel returned(world) Resetting... 1st section: time through returned(another) 2nd section: anothes returned(anothet) 3rd section: The end is near - goodbye cruel returned(through)

Caution: Contents may have been coded under pressure.

In reply to (non-)Obfu Coroutines by Roy Johnson
in thread Obfu Coroutines by Limbic~Region

Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post; it's "PerlMonks-approved HTML":

  • Are you posting in the right place? Check out Where do I post X? to know for sure.
  • Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
    <code> <a> <b> <big> <blockquote> <br /> <dd> <dl> <dt> <em> <font> <h1> <h2> <h3> <h4> <h5> <h6> <hr /> <i> <li> <nbsp> <ol> <p> <small> <strike> <strong> <sub> <sup> <table> <td> <th> <tr> <tt> <u> <ul>
  • Snippets of code should be wrapped in <code> tags not <pre> tags. In fact, <pre> tags should generally be avoided. If they must be used, extreme care should be taken to ensure that their contents do not have long lines (<70 chars), in order to prevent horizontal scrolling (and possible janitor intervention).
  • Want more info? How to link or or How to display code and escape characters are good places to start.
Log In?

What's my password?
Create A New User
Domain Nodelet?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others scrutinizing the Monastery: (3)
As of 2022-05-20 15:05 GMT
Find Nodes?
    Voting Booth?
    Do you prefer to work remotely?

    Results (73 votes). Check out past polls.