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

EXCEPTIONS

138       Guard blocks should not normally throw exceptions (that is, "die").
139       After all, they are usually used to clean up after such exceptions.
140       However, if something truly exceptional is happening, a guard block
141       should be allowed to die. Also, programming errors are a large source
142       of exceptions, and the programmer certainly wants to know 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, followed by calling the code reference stored in $Guard::DIED
150       (with $@ set to the actual exception), which is similar to how most
151       event loops handle this case.
152
153       The default for $Guard::DIED is to call "warn "$@"".
154
155       The $@ variable will be restored to its value before the guard call in
156       all cases, so guards will not disturb $@ in any way.
157
158       The code reference stored in $Guard::DIED should not die (behaviour is
159       not guaranteed, but right now, the exception will simply be ignored).
160

AUTHOR

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

THANKS

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

SEE ALSO

170       Scope::Guard and Sub::ScopeFinalizer, which actually implement dynamic,
171       not scoped guards, and have a lot higher CPU, memory and typing
172       overhead.
173
174       Hook::Scope, which has apparently never been finished and corrupts
175       memory when used.
176
177
178
179perl v5.12.0                      2009-07-19                          Guard(3)
Impressum