--- Guard/Guard.pm 2008/12/13 18:44:16 1.7 +++ Guard/Guard.pm 2008/12/13 18:50:31 1.10 @@ -4,16 +4,16 @@ =head1 SYNOPSIS - 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"; - - call_function_that_might_die_or_other_fun_stuff; - } + 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"; + + call_function_that_might_die_or_other_fun_stuff; + } =head1 DESCRIPTION @@ -54,11 +54,14 @@ Registers a block that is executed when the current scope (block, function, method, eval etc.) is exited. +See the EXCEPTIONS section for an explanation of how exceptions +(i.e. C) are handled inside guard blocks. + The description below sounds a bit complicated, but that's just because C tries to get even corner cases "right": the goal is to provide you with a rock solid clean up tool. -This is similar to this code fragment: +The behaviour is similar to this code fragment: eval ... code following scope_guard ... { @@ -72,12 +75,9 @@ BLOCK calls C, C, C or escapes via other means. If multiple BLOCKs are registered to the same scope, they will be executed -in reverse order. Stuff like C is managed via the same mechanism, -so variables Cised after calling C will be restored -when the guard runs. - -See B, below, for an explanation of exception handling -(C) within guard blocks. +in reverse order. Other scope-related things such as C are managed +via the same mechanism, so variables Cised I calling +C will be restored when the guard runs. Example: temporarily change the timezone for the current process, ensuring it will be reset when the C scope is exited: @@ -105,18 +105,21 @@ The returned object can be copied as many times as you want. -See B, below, for an explanation of exception handling -(C) within guard blocks. +See the EXCEPTIONS section for an explanation of how exceptions +(i.e. C) are handled inside guard blocks. Example: acquire a Coro::Semaphore for a second by registering a -timer. The timer callback references the guard used to unlock it again. +timer. The timer callback references the guard used to unlock it +again. (Please ignore the fact that C has a C +method that does this already): + use Guard; use AnyEvent; use Coro::Semaphore; my $sem = new Coro::Semaphore; - sub lock_1s { + sub lock_for_a_second { $sem->down; my $guard = guard { $sem->up };