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 = csub { |
11 |
result $_*2; |
12 |
result $_; |
13 |
}; |
14 |
my %hash2 = map &$csub, &hash1; |
15 |
|
16 |
# dasselbe in grĂ¼n (as we germans say) |
17 |
sub mul2 : Cont { |
18 |
result $_*2; |
19 |
result $_; |
20 |
} |
21 |
|
22 |
my %hash2 = map mul2, &hash1; |
23 |
|
24 |
|
25 |
=head1 DESCRIPTION |
26 |
|
27 |
=over 4 |
28 |
|
29 |
=cut |
30 |
|
31 |
package Coro::Cont; |
32 |
|
33 |
use Coro::State; |
34 |
use Coro::Specific; |
35 |
|
36 |
use base 'Exporter'; |
37 |
|
38 |
$VERSION = 0.08; |
39 |
@EXPORT = qw(csub result); |
40 |
|
41 |
{ |
42 |
use subs 'csub'; |
43 |
|
44 |
my @csub; |
45 |
|
46 |
# this way of handling attributes simply is NOT scalable ;() |
47 |
sub import { |
48 |
Coro::Cont->export_to_level(1, @_); |
49 |
my $old = *{(caller)[0]."::MODIFY_CODE_ATTRIBUTES"}{CODE}; |
50 |
no warnings; |
51 |
*{(caller)[0]."::MODIFY_CODE_ATTRIBUTES"} = sub { |
52 |
my ($package, $ref) = (shift, shift); |
53 |
my @attrs; |
54 |
for (@_) { |
55 |
if ($_ eq "Cont") { |
56 |
push @csub, $ref; |
57 |
} else { |
58 |
push @attrs, $_; |
59 |
} |
60 |
} |
61 |
return $old ? $old->($package, $ref, @attrs) : @attrs; |
62 |
}; |
63 |
} |
64 |
|
65 |
sub INIT { |
66 |
for (@csub) { |
67 |
$$_ = csub $$_; |
68 |
} |
69 |
@csub = (); |
70 |
} |
71 |
} |
72 |
|
73 |
=item csub { ... } |
74 |
|
75 |
Create a new "continuation" (when the sub falls of the end it is being |
76 |
terminated). |
77 |
|
78 |
=cut |
79 |
|
80 |
our $curr = new Coro::Specific; |
81 |
our @result; |
82 |
|
83 |
sub csub(&) { |
84 |
my $code = $_[0]; |
85 |
my $coro = new Coro::State sub { &$code while 1 }; |
86 |
my $prev = new Coro::State; |
87 |
sub { |
88 |
push @$$curr, [$coro, $prev]; |
89 |
&Coro::State::transfer($prev, $coro, 0); |
90 |
wantarray ? @{pop @result} : ${pop @result}[0]; |
91 |
}; |
92 |
} |
93 |
|
94 |
=item result [list] |
95 |
|
96 |
Return the given list/scalar as result of the continuation. |
97 |
|
98 |
=cut |
99 |
|
100 |
sub result { |
101 |
push @result, [@_]; |
102 |
&Coro::State::transfer(@{pop @$$curr}, 0); |
103 |
@_; |
104 |
} |
105 |
|
106 |
1; |
107 |
|
108 |
=back |
109 |
|
110 |
=head1 AUTHOR |
111 |
|
112 |
Marc Lehmann <pcg@goof.com> |
113 |
http://www.goof.com/pcg/marc/ |
114 |
|
115 |
=cut |
116 |
|