1Guard(3)              User Contributed Perl Documentation             Guard(3)
2
3
4

NAME

6       Guard - safe cleanup blocks
7

SYNOPSIS

9          use Guard;
10
11          # temporarily chdir to "/etc" directory, but make sure
12          # to go back to "/" no matter how myfun exits:
13          sub myfun {
14             scope_guard { chdir "/" };
15             chdir "/etc";
16
17             code_that_might_die_or_does_other_fun_stuff;
18          }
19
20          # create an object that, when the last reference to it is gone,
21          # invokes the given codeblock:
22          my $guard = guard { print "destroyed!\n" };
23          undef $guard; # probably destroyed here
24

DESCRIPTION

26       This module implements so-called "guards". A guard is something
27       (usually an object) that "guards" a resource, ensuring that it is
28       cleaned up when expected.
29
30       Specifically, this module supports two different types of guards: guard
31       objects, which execute a given code block when destroyed, and scoped
32       guards, which are tied to the scope exit.
33

FUNCTIONS

35       This module currently exports the "scope_guard" and "guard" functions
36       by default.
37
38       scope_guard BLOCK
39       scope_guard ($coderef)
40           Registers a block that is executed when the current scope (block,
41           function, method, eval etc.) is exited.
42
43           See the EXCEPTIONS section for an explanation of how exceptions
44           (i.e. "die") are handled inside guard blocks.
45
46           The description below sounds a bit complicated, but that's just
47           because "scope_guard" tries to get even corner cases "right": the
48           goal is to provide you with a rock solid clean up tool.
49
50           The behaviour is similar to this code fragment:
51
52              eval ... code following scope_guard ...
53              {
54                 local $@;
55                 eval BLOCK;
56                 eval { $Guard::DIED->() } if $@;
57              }
58              die if $@;
59
60           Except it is much faster, and the whole thing gets executed even
61           when the BLOCK calls "exit", "goto", "last" or escapes via other
62           means.
63
64           If multiple BLOCKs are registered to the same scope, they will be
65           executed in reverse order. Other scope-related things such as
66           "local" are managed via the same mechanism, so variables
67           "local"ised after calling "scope_guard" will be restored when the
68           guard runs.
69
70           Example: temporarily change the timezone for the current process,
71           ensuring it will be reset when the "if" scope is exited:
72
73              use Guard;
74              use POSIX ();
75
76              if ($need_to_switch_tz) {
77                 # make sure we call tzset after $ENV{TZ} has been restored
78                 scope_guard { POSIX::tzset };
79
80                 # localise after the scope_guard, so it gets undone in time
81                 local $ENV{TZ} = "Europe/London";
82                 POSIX::tzset;
83
84                 # do something with the new timezone
85              }
86
87       my $guard = guard BLOCK
88       my $guard = guard ($coderef)
89           Behaves the same as "scope_guard", except that instead of executing
90           the block on scope exit, it returns an object whose lifetime
91           determines when the BLOCK gets executed: when the last reference to
92           the object gets destroyed, the BLOCK gets executed as with
93           "scope_guard".
94
95           See the EXCEPTIONS section for an explanation of how exceptions
96           (i.e. "die") are handled inside guard blocks.
97
98           Example: acquire a Coro::Semaphore for a second by registering a
99           timer. The timer callback references the guard used to unlock it
100           again. (Please ignore the fact that "Coro::Semaphore" has a "guard"
101           method that does this already):
102
103              use Guard;
104              use Coro::AnyEvent;
105              use Coro::Semaphore;
106
107              my $sem = new Coro::Semaphore;
108
109              sub lock_for_a_second {
110                 $sem->down;
111                 my $guard = guard { $sem->up };
112
113                 Coro::AnyEvent::sleep 1;
114
115                 # $sem->up gets executed when returning
116              }
117
118           The advantage of doing this with a guard instead of simply calling
119           "$sem->down" in the callback is that you can opt not to create the
120           timer, or your code can throw an exception before it can create the
121           timer (or the thread gets canceled), or you can create multiple
122           timers or other event watchers and only when the last one gets
123           executed will the lock be unlocked. Using the "guard", you do not
124           have to worry about catching all the places where you have to
125           unlock the semaphore.
126
127       $guard->cancel
128           Calling this function will "disable" the guard object returned by
129           the "guard" function, i.e. it will free the BLOCK originally passed
130           to "guard "and will arrange for the BLOCK not to be executed.
131
132           This can be useful when you use "guard" to create a cleanup handler
133           to be called under fatal conditions and later decide it is no
134           longer needed.
135

EXCEPTIONS

137       Guard blocks should not normally throw exceptions (that is, "die").
138       After all, they are usually used to clean up after such exceptions.
139       However, if something truly exceptional is happening, a guard block
140       should of course be allowed to die. Also, programming errors are a
141       large source of exceptions, and the programmer certainly wants to know
142       about those.
143
144       Since in most cases, the block executing when the guard gets executed
145       does not know or does not care about the guard blocks, it makes little
146       sense to let containing code handle the exception.
147
148       Therefore, whenever a guard block throws an exception, it will be
149       caught by Guard, followed by calling the code reference stored in
150       $Guard::DIED (with $@ set to the actual exception), which is similar to
151       how most event loops handle this case.
152
153       The default for $Guard::DIED is to call "warn "$@"", i.e. the error is
154       printed as a warning and the program continues.
155
156       The $@ variable will be restored to its value before the guard call in
157       all cases, so guards will not disturb $@ in any way.
158
159       The code reference stored in $Guard::DIED should not die (behaviour is
160       not guaranteed, but right now, the exception will simply be ignored).
161

AUTHOR

163        Marc Lehmann <schmorp@schmorp.de>
164        http://home.schmorp.de/
165

THANKS

167       Thanks to Marco Maisenhelder, who reminded me of the $Guard::DIED
168       solution to the problem of exceptions.
169

SEE ALSO

171       Scope::Guard and Sub::ScopeFinalizer, which actually implement
172       dynamically scoped guards only, not the lexically scoped guards that
173       their documentation promises, and have a lot higher CPU, memory and
174       typing overhead.
175
176       Hook::Scope, which has apparently never been finished and can corrupt
177       memory when used.
178
179       Scope::Guard seems to have a big SEE ALSO section for even more modules
180       like it.
181
182
183
184perl v5.32.1                      2021-01-27                          Guard(3)
Impressum