.\" -*- mode: troff; coding: utf-8 -*- .\" Automatically generated by Pod::Man 5.01 (Pod::Simple 3.43) .\" .\" Standard preamble: .\" ======================================================================== .de Sp \" Vertical space (when we can't use .PP) .if t .sp .5v .if n .sp .. .de Vb \" Begin verbatim text .ft CW .nf .ne \\$1 .. .de Ve \" End verbatim text .ft R .fi .. .\" \*(C` and \*(C' are quotes in nroff, nothing in troff, for use with C<>. .ie n \{\ . ds C` "" . ds C' "" 'br\} .el\{\ . ds C` . ds C' 'br\} .\" .\" Escape single quotes in literal strings from groff's Unicode transform. .ie \n(.g .ds Aq \(aq .el .ds Aq ' .\" .\" If the F register is >0, we'll generate index entries on stderr for .\" titles (.TH), headers (.SH), subsections (.SS), items (.Ip), and index .\" entries marked with X<> in POD. Of course, you'll have to process the .\" output yourself in some meaningful fashion. .\" .\" Avoid warning from groff about undefined register 'F'. .de IX .. .nr rF 0 .if \n(.g .if rF .nr rF 1 .if (\n(rF:(\n(.g==0)) \{\ . if \nF \{\ . de IX . tm Index:\\$1\t\\n%\t"\\$2" .. . if !\nF==2 \{\ . nr % 0 . nr F 2 . \} . \} .\} .rr rF .\" ======================================================================== .\" .IX Title "Guard 3pm" .TH Guard 3pm 2024-01-10 "perl v5.38.2" "User Contributed Perl Documentation" .\" For nroff, turn off justification. Always turn off hyphenation; it makes .\" way too many mistakes in technical documents. .if n .ad l .nh .SH NAME Guard \- safe cleanup blocks .SH SYNOPSIS .IX Header "SYNOPSIS" .Vb 1 \& use Guard; \& \& # temporarily chdir to "/etc" directory, but make sure \& # to go back to "/" no matter how myfun exits: \& sub myfun { \& scope_guard { chdir "/" }; \& chdir "/etc"; \& \& code_that_might_die_or_does_other_fun_stuff; \& } \& \& # create an object that, when the last reference to it is gone, \& # invokes the given codeblock: \& my $guard = guard { print "destroyed!\en" }; \& undef $guard; # probably destroyed here .Ve .SH DESCRIPTION .IX Header "DESCRIPTION" This module implements so-called "guards". A guard is something (usually an object) that "guards" a resource, ensuring that it is cleaned up when expected. .PP Specifically, this module supports two different types of guards: guard objects, which execute a given code block when destroyed, and scoped guards, which are tied to the scope exit. .SH FUNCTIONS .IX Header "FUNCTIONS" This module currently exports the \f(CW\*(C`scope_guard\*(C'\fR and \f(CW\*(C`guard\*(C'\fR functions by default. .IP "scope_guard BLOCK" 4 .IX Item "scope_guard BLOCK" .PD 0 .IP "scope_guard ($coderef)" 4 .IX Item "scope_guard ($coderef)" .PD Registers a block that is executed when the current scope (block, function, method, eval etc.) is exited. .Sp See the EXCEPTIONS section for an explanation of how exceptions (i.e. \f(CW\*(C`die\*(C'\fR) are handled inside guard blocks. .Sp The description below sounds a bit complicated, but that's just because \&\f(CW\*(C`scope_guard\*(C'\fR tries to get even corner cases "right": the goal is to provide you with a rock solid clean up tool. .Sp The behaviour is similar to this code fragment: .Sp .Vb 7 \& eval ... code following scope_guard ... \& { \& local $@; \& eval BLOCK; \& eval { $Guard::DIED\->() } if $@; \& } \& die if $@; .Ve .Sp Except it is much faster, and the whole thing gets executed even when the BLOCK calls \f(CW\*(C`exit\*(C'\fR, \f(CW\*(C`goto\*(C'\fR, \f(CW\*(C`last\*(C'\fR or escapes via other means. .Sp If multiple BLOCKs are registered to the same scope, they will be executed in reverse order. Other scope-related things such as \f(CW\*(C`local\*(C'\fR are managed via the same mechanism, so variables \f(CW\*(C`local\*(C'\fRised \fIafter\fR calling \&\f(CW\*(C`scope_guard\*(C'\fR will be restored when the guard runs. .Sp Example: temporarily change the timezone for the current process, ensuring it will be reset when the \f(CW\*(C`if\*(C'\fR scope is exited: .Sp .Vb 2 \& use Guard; \& use POSIX (); \& \& if ($need_to_switch_tz) { \& # make sure we call tzset after $ENV{TZ} has been restored \& scope_guard { POSIX::tzset }; \& \& # localise after the scope_guard, so it gets undone in time \& local $ENV{TZ} = "Europe/London"; \& POSIX::tzset; \& \& # do something with the new timezone \& } .Ve .ie n .IP "my $guard = guard BLOCK" 4 .el .IP "my \f(CW$guard\fR = guard BLOCK" 4 .IX Item "my $guard = guard BLOCK" .PD 0 .ie n .IP "my $guard = guard ($coderef)" 4 .el .IP "my \f(CW$guard\fR = guard ($coderef)" 4 .IX Item "my $guard = guard ($coderef)" .PD Behaves the same as \f(CW\*(C`scope_guard\*(C'\fR, except that instead of executing the block on scope exit, it returns an object whose lifetime determines when the BLOCK gets executed: when the last reference to the object gets destroyed, the BLOCK gets executed as with \f(CW\*(C`scope_guard\*(C'\fR. .Sp See the EXCEPTIONS section for an explanation of how exceptions (i.e. \f(CW\*(C`die\*(C'\fR) are handled inside guard blocks. .Sp Example: acquire a Coro::Semaphore for a second by registering a timer. The timer callback references the guard used to unlock it again. (Please ignore the fact that \f(CW\*(C`Coro::Semaphore\*(C'\fR has a \f(CW\*(C`guard\*(C'\fR method that does this already): .Sp .Vb 3 \& use Guard; \& use Coro::AnyEvent; \& use Coro::Semaphore; \& \& my $sem = new Coro::Semaphore; \& \& sub lock_for_a_second { \& $sem\->down; \& my $guard = guard { $sem\->up }; \& \& Coro::AnyEvent::sleep 1; \& \& # $sem\->up gets executed when returning \& } .Ve .Sp The advantage of doing this with a guard instead of simply calling \f(CW\*(C`$sem\->down\*(C'\fR in the callback is that you can opt not to create the timer, or your code can throw an exception before it can create the timer (or the thread gets canceled), or you can create multiple timers or other event watchers and only when the last one gets executed will the lock be unlocked. Using the \f(CW\*(C`guard\*(C'\fR, you do not have to worry about catching all the places where you have to unlock the semaphore. .ie n .IP $guard\->cancel 4 .el .IP \f(CW$guard\fR\->cancel 4 .IX Item "$guard->cancel" Calling this function will "disable" the guard object returned by the \&\f(CW\*(C`guard\*(C'\fR function, i.e. it will free the BLOCK originally passed to \&\f(CW\*(C`guard \*(C'\fRand will arrange for the BLOCK not to be executed. .Sp This can be useful when you use \f(CW\*(C`guard\*(C'\fR to create a cleanup handler to be called under fatal conditions and later decide it is no longer needed. .SH EXCEPTIONS .IX Header "EXCEPTIONS" Guard blocks should not normally throw exceptions (that is, \f(CW\*(C`die\*(C'\fR). After all, they are usually used to clean up after such exceptions. However, if something truly exceptional is happening, a guard block should of course be allowed to die. Also, programming errors are a large source of exceptions, and the programmer certainly wants to know about those. .PP Since in most cases, the block executing when the guard gets executed does not know or does not care about the guard blocks, it makes little sense to let containing code handle the exception. .PP Therefore, whenever a guard block throws an exception, it will be caught by Guard, followed by calling the code reference stored in \f(CW$Guard::DIED\fR (with \f(CW$@\fR set to the actual exception), which is similar to how most event loops handle this case. .PP The default for \f(CW$Guard::DIED\fR is to call \f(CW\*(C`warn "$@"\*(C'\fR, i.e. the error is printed as a warning and the program continues. .PP The \f(CW$@\fR variable will be restored to its value before the guard call in all cases, so guards will not disturb \f(CW$@\fR in any way. .PP The code reference stored in \f(CW$Guard::DIED\fR should not die (behaviour is not guaranteed, but right now, the exception will simply be ignored). .SH AUTHOR .IX Header "AUTHOR" .Vb 2 \& Marc Lehmann \& http://home.schmorp.de/ .Ve .SH THANKS .IX Header "THANKS" Thanks to Marco Maisenhelder, who reminded me of the \f(CW$Guard::DIED\fR solution to the problem of exceptions. .SH "SEE ALSO" .IX Header "SEE ALSO" Scope::Guard and Sub::ScopeFinalizer, which actually implement dynamically scoped guards only, not the lexically scoped guards that their documentation promises, and have a lot higher CPU, memory and typing overhead. .PP Hook::Scope, which has apparently never been finished and can corrupt memory when used. .PP Scope::Guard seems to have a big SEE ALSO section for even more modules like it.