1package Scope::Guard;
2
3use strict;
4use warnings;
5
6use vars qw($VERSION);
7
8$VERSION = '0.03';
9
10sub new {
11    my $class = shift;
12    my $handler = shift() || die "Scope::Guard::new: no handler supplied";
13    my $ref = ref $handler || '';
14
15    die "Scope::Guard::new: invalid handler - expected CODE ref, got: '$ref'"
16	unless (UNIVERSAL::isa($handler, 'CODE'));
17
18    bless [ 0, $handler ], ref $class || $class;
19}
20
21sub dismiss {
22    my $self = shift;
23    my $dismiss = @_ ? shift : 1;
24
25    $self->[0] = $dismiss;
26}
27
28sub DESTROY {
29    my $self = shift;
30    my ($dismiss, $handler) = @$self;
31
32    $handler->() unless ($dismiss);
33}
34
351;
36
37__END__
38
39=pod
40
41=head1 NAME
42
43Scope::Guard - lexically scoped resource management
44
45=head1 SYNOPSIS
46
47	my $sg = Scope::Guard->new(sub { ... });
48
49	  # or
50
51	my $sg = Scope::Guard->new(\&handler);
52
53	$sg->dismiss(); # disable the handler
54
55=head1 DESCRIPTION
56
57This module provides a convenient way to perform cleanup or other forms of resource
58management at the end of a scope. It is particularly useful when dealing with exceptions:
59the Scope::Guard constructor takes a reference to a subroutine that is guaranteed to
60be called even if the thread of execution is aborted prematurely. This effectively allows
61lexically-scoped "promises" to be made that are automatically honoured by perl's garbage
62collector.
63
64For more information, see: L<http://www.cuj.com/documents/s=8000/cujcexp1812alexandr/>
65
66=head2 new
67
68=head3 usage
69
70    my $sg = Scope::Guard->new(sub { ... });
71
72	  # or
73
74    my $sg = Scope::Guard->new(\&handler);
75
76=head3 description
77
78Create a new Scope::Guard object which calls the supplied handler when its C<DESTROY> method is
79called, typically when it goes out of scope.
80
81=head2 dismiss
82
83=head3 usage
84
85    $sg->dismiss();
86
87	  # or
88
89    $sg->dismiss(1);
90
91=head3 description
92
93Detach the handler from the Scope::Guard object. This revokes the "promise" to call the
94handler when the object is destroyed.
95
96The handler can be re-enabled by calling:
97
98	$sg->dismiss(0);
99
100=head1 VERSION
101
1020.03
103
104=head1 SEE ALSO
105
106=over
107
108=item * L<Hook::LexWrap|Hook::LexWrap>
109
110=item * L<Hook::Scope|Hook::Scope>
111
112=item * L<Sub::ScopeFinalizer|Sub::ScopeFinalizer>
113
114=item * L<Object::Destroyer|Object::Destroyer>
115
116=back
117
118=head1 AUTHOR
119
120chocolateboy: <chocolate.boy@email.com>
121
122=head1 COPYRIGHT
123
124Copyright (c) 2005-2007, chocolateboy.
125
126This module is free software. It may be used, redistributed and/or modified under the same terms
127as Perl itself.
128
129=cut
130