1 |
root |
1.1 |
=head1 NAME |
2 |
|
|
|
3 |
|
|
Coro::Cont - schmorp's faked continuations |
4 |
|
|
|
5 |
|
|
=head1 SYNOPSIS |
6 |
|
|
|
7 |
|
|
use Coro::Cont; |
8 |
|
|
|
9 |
|
|
# multiply all hash keys by 2 |
10 |
|
|
my $cont = cont { |
11 |
|
|
result $_*2; |
12 |
|
|
result $_; |
13 |
|
|
}; |
14 |
|
|
my %hash2 = map &$cont, &hash1; |
15 |
|
|
|
16 |
|
|
|
17 |
|
|
=head1 DESCRIPTION |
18 |
|
|
|
19 |
|
|
=over 4 |
20 |
|
|
|
21 |
|
|
=cut |
22 |
|
|
|
23 |
|
|
package Coro::Cont; |
24 |
|
|
|
25 |
|
|
use Coro::State; |
26 |
|
|
use Coro::Specific; |
27 |
|
|
|
28 |
|
|
use base 'Exporter'; |
29 |
|
|
|
30 |
|
|
$VERSION = 0.01; |
31 |
|
|
@EXPORT = qw(cont result); |
32 |
|
|
|
33 |
|
|
=item cont { ... } |
34 |
|
|
|
35 |
|
|
Create a new "continuation" (well, almost, you cannot return from it). |
36 |
|
|
|
37 |
|
|
=cut |
38 |
|
|
|
39 |
|
|
our $curr = new Coro::Specific; |
40 |
|
|
our @result; |
41 |
|
|
|
42 |
|
|
sub cont(&) { |
43 |
|
|
my $code = $_[0]; |
44 |
root |
1.2 |
my $coro = new Coro::State sub { &$code while 1 }; |
45 |
root |
1.1 |
my $prev = new Coro::State; |
46 |
|
|
sub { |
47 |
|
|
push @$$curr, [$coro, $prev]; |
48 |
|
|
$prev->transfer($coro); |
49 |
|
|
wantarray ? @{pop @result} : ${pop @result}[0]; |
50 |
|
|
}; |
51 |
|
|
} |
52 |
|
|
|
53 |
|
|
=item result [list] |
54 |
|
|
|
55 |
|
|
Return the given list/scalar as result of the continuation. |
56 |
|
|
|
57 |
|
|
=cut |
58 |
|
|
|
59 |
|
|
sub result { |
60 |
|
|
push @result, [@_]; |
61 |
|
|
&Coro::State::transfer(@{pop @$$curr}); |
62 |
|
|
} |
63 |
|
|
|
64 |
|
|
1; |
65 |
|
|
|
66 |
|
|
=back |
67 |
|
|
|
68 |
|
|
=head1 AUTHOR |
69 |
|
|
|
70 |
|
|
Marc Lehmann <pcg@goof.com> |
71 |
|
|
http://www.goof.com/pcg/marc/ |
72 |
|
|
|
73 |
|
|
=cut |
74 |
|
|
|