bfab9f0c26b7a56381c2b7205ef9d81045eaae0d
[p5sagit/B-Hooks-EndOfScope-WithFallback.git] / lib / B / Hooks / EndOfScope.pm
1 use strict;
2 use warnings;
3
4 package B::Hooks::EndOfScope;
5 # ABSTRACT: Execute code after a scope finished compilation
6
7 use 5.008000;
8 use Variable::Magic 0.34;
9
10 use Sub::Exporter -setup => {
11     exports => ['on_scope_end'],
12     groups  => { default => ['on_scope_end'] },
13 };
14
15
16 =head1 SYNOPSIS
17
18     on_scope_end { ... };
19
20 =head1 DESCRIPTION
21
22 This module allows you to execute code when perl finished compiling the
23 surrounding scope.
24
25 =func on_scope_end
26
27     on_scope_end { ... };
28
29     on_scope_end $code;
30
31 Registers C<$code> to be executed after the surrounding scope has been
32 compiled.
33
34 This is exported by default. See L<Sub::Exporter> on how to customize it.
35
36 =cut
37
38 {
39     my $wiz = Variable::Magic::wizard
40         data => sub { [$_[1]] },
41         free => sub { $_->() for @{ $_[1] }; () };
42
43     sub on_scope_end (&) {
44         my $cb = shift;
45
46         $^H |= 0x020000;
47
48         if (my $stack = Variable::Magic::getdata %^H, $wiz) {
49             push @{ $stack }, $cb;
50         }
51         else {
52             Variable::Magic::cast %^H, $wiz, $cb;
53         }
54     }
55 }
56
57 =head1 SEE ALSO
58
59 L<Sub::Exporter>
60
61 L<Variable::Magic>
62
63 =cut
64
65 1;