1Scope::Guard(3) User Contributed Perl Documentation Scope::Guard(3)
2
3
4
6 Scope::Guard - lexically-scoped resource management
7
9 my $guard = guard { ... };
10
11 # or
12
13 my $guard = scope_guard \&handler;
14
15 # or
16
17 my $guard = Scope::Guard->new(sub { ... });
18
19 $guard->dismiss(); # disable the handler
20
22 This module provides a convenient way to perform cleanup or other forms
23 of resource management at the end of a scope. It is particularly useful
24 when dealing with exceptions: the "Scope::Guard" constructor takes a
25 reference to a subroutine that is guaranteed to be called even if the
26 thread of execution is aborted prematurely. This effectively allows
27 lexically-scoped "promises" to be made that are automatically honoured
28 by perl's garbage collector.
29
30 For more information, see: <http://www.drdobbs.com/cpp/184403758>
31
33 new
34 my $guard = Scope::Guard->new(sub { ... });
35
36 # or
37
38 my $guard = Scope::Guard->new(\&handler);
39
40 The "new" method creates a new "Scope::Guard" object which calls the
41 supplied handler when its "DESTROY" method is called, typically at the
42 end of the scope.
43
44 dismiss
45 $guard->dismiss();
46
47 # or
48
49 $guard->dismiss(1);
50
51 "dismiss" detaches the handler from the "Scope::Guard" object. This
52 revokes the "promise" to call the handler when the object is destroyed.
53
54 The handler can be re-enabled by calling:
55
56 $guard->dismiss(0);
57
59 guard
60 "guard" takes a block and returns a new "Scope::Guard" object. It can
61 be used as a shorthand for:
62
63 Scope::Guard->new(...)
64
65 e.g.
66
67 my $guard = guard { ... };
68
69 Note: calling "guard" anonymously, i.e. in void context, will raise an
70 exception. This is because anonymous guards are destroyed immediately
71 (rather than at the end of the scope), which is unlikely to be the
72 desired behaviour.
73
74 scope_guard
75 "scope_guard" is the same as "guard", but it takes a code ref rather
76 than a block. e.g.
77
78 my $guard = scope_guard \&handler;
79
80 or:
81
82 my $guard = scope_guard sub { ... };
83
84 or:
85
86 my $guard = scope_guard $handler;
87
88 As with "guard", calling "scope_guard" in void context will raise an
89 exception.
90
92 0.21
93
95 • B::Hooks::EndOfScope
96
97 • End
98
99 • Guard
100
101 • Hook::Scope
102
103 • Object::Destroyer
104
105 • Perl::AtEndOfScope
106
107 • ReleaseAction
108
109 • Scope::local_OnExit
110
111 • Scope::OnExit
112
113 • Sub::ScopeFinalizer
114
115 • Value::Canary
116
118 chocolateboy <chocolate@cpan.org>
119
121 Copyright (c) 2005-2015, chocolateboy.
122
123 This module is free software. It may be used, redistributed and/or
124 modified under the same terms as Perl itself.
125
126
127
128perl v5.32.1 2021-01-27 Scope::Guard(3)