3 ms·
A closer equivalent in perl, and other similar languages with closures, is the manually-unrolled continuation: sub continuationish { my $args = shi
by jerf 16y ago
A closer equivalent in perl, and other similar languages with closures, is the manually-unrolled continuation:
sub continuationish {
my $args = shift;
my $state = {args => $args, state => 'INIT'};
return sub {
goto $state->{state};
INIT: {
# initial setup...
$state->{state} = 'NORMAL';
return $first_output;
}
NORMAL: {
# do stuff
if (!$almost_done) {
return $next_thingy;
} else {
$state->{state} = 'TERMINATING';
return $next_thingy;
}
}
TERMINATING: {
$state->{state} = 'TERMINATED';
return $state->{last_thingy}; # set above somewhere
}
TERMINATED: {
return $sentinal_value;
}
};
}
Everywhere you'd use a variable, you have to use something out of $state. This works. Any function can be rewritten using this approach to become a "generator" in Perl or similar languages. (Just remember that for and while loops all ultimately compile to "goto"s, and just perform the transform yourself.) But... you'll come to appreciate continuations or Python's yield pretty quickly. I think there have been three functions in my ~10 years of perl programming where I deemed it worth jumping through these hoops. Nice tool, but if you're using it a lot something's wrong.
There exist some modules that try to do this automatically, however I have had some trouble with them, and they have the major problem that they end up being relatively opaque, often involving things like source code filters. Also, the module documentation can feed you bad ideas about this enabling multithreading or being a good idea for routine use; in fact it doesn't affect threading at all and I'd run screaming from any module written by an author confused enough to think it's related even tangentially to multithreading. Since you really shouldn't be doing this all the time, I actually recommend doing it manually in a Perl-like language, or switching to a language that has much better support for this style if at all possible. YMMV.