Guard(3)

πŸ’– Guard(3) β€” safe cleanup blocks πŸ’–

okay bestie, so this one's the Guard page from the User Contributed Perl Documentation, and honestly? it's a whole vibe. it's about making sure your stuff gets cleaned up. no cap.


✨ NAME ✨

Guard β€” safe cleanup blocks. that's it. that's the tweet. πŸŽ€


πŸ¦‹ 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";

   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!\n" };
undef $guard; # probably destroyed here

like, look at that second one. undef $guard; and boom πŸ’€ destroyed. main character energy fr.


🌸 DESCRIPTION 🌸

so this module implements what everyone calls "guards." a guard is a thing (usually an object) that literally guards a resource and makes sure it gets cleaned up exactly when you expect it to. it's giving bodyguard but for memory and filehandles tbh 🫢

specifically, this module supports two different types of guards: guard objects, which execute a given code block when they get destroyed, and scoped guards, which are tied to the scope exit. two flavors, both iconic. πŸ’…


⭐ FUNCTIONS ⭐

this module currently exports the scope_guard and guard functions by default. so you don't even have to ask. they just show up. 😌

🧚 scope_guard BLOCK

🧚 scope_guard ($coderef)

registers a block that gets executed when the current scope (block, function, method, eval, etc.) is exited. lowkey the whole point.

see the EXCEPTIONS section for the whole explanation of how exceptions (like, die) are handled inside guard blocks. important, don't skip it. πŸ™ˆ

okay the description below sounds a bit complicated, but that's literally just because scope_guard tries to get even the corner cases "right" β€” the goal is to hand you a rock solid cleanup tool. that's the assignment and it ate. πŸ”₯

the behaviour is similar to this code fragment:

eval ... code following scope_guard ...
{
   local $@;
   eval BLOCK;
   eval { $Guard::DIED->() } if $@;
}
die if $@;

except it's much faster, and the whole thing gets executed even when the BLOCK calls exit, goto, last, or escapes via other means. yeah. it does not care. it's doing its job regardless. πŸ‘‘

if multiple BLOCKs are registered to the same scope, they get executed in reverse order. other scope-related things like local are managed via the same mechanism, so variables localised after calling scope_guard will be restored when the guard runs. timing matters bestie ⏰

example: temporarily change the timezone for the current process, ensuring it gets reset when the if scope is exited:

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
}

see how the local comes after the scope_guard? that's not an accident, that's on purpose. πŸŽ€

πŸ¦‹ my $guard = guard BLOCK

πŸ¦‹ my $guard = guard ($coderef)

behaves the same as scope_guard, except that instead of executing the block on scope exit, it returns an object whose lifetime determines when the BLOCK gets executed. so when the last reference to that object gets destroyed, the BLOCK gets executed, same as with scope_guard. it's the same energy, different delivery. πŸ’«

see the EXCEPTIONS section for how exceptions (like, die) are handled inside guard blocks. yes, again. go read it. 🫢

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 Coro::Semaphore has a guard method that does this already πŸ™ˆ)

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
}

the advantage of doing this with a guard instead of just calling $sem->down 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 guard, you do not have to worry about catching all the places where you have to unlock the semaphore. like, that's so many places. who has the time. not us. πŸ’…

πŸ’€ $guard->cancel

calling this function will "disable" the guard object returned by the guard function, i.e. it will free the BLOCK originally passed to guard and will arrange for the BLOCK not to be executed.

this can be useful when you use guard to create a cleanup handler to be called under fatal conditions and later decide it is no longer needed. plot twist: you don't need the cleanup anymore. cancel. goodbye. ✌️


😭 EXCEPTIONS 😭

guard blocks should not normally throw exceptions (that is, die). after all, they're usually used to clean up after such exceptions. like, read the room. πŸ˜…

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. fair. valid. we respect it.

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.

therefore, whenever a guard block throws an exception, it will be caught by Guard, followed by calling the code reference stored in $Guard::DIED (with $@ set to the actual exception), which is similar to how most event loops handle this case. slay, consistent behaviour. πŸ”₯

the default for $Guard::DIED is to call warn "$@", i.e. the error is printed as a warning and the program continues. no drama, just a warning. 🌈

the $@ variable will be restored to its value before the guard call in all cases, so guards will not disturb $@ in any way. bestie would never. 🫢

the code reference stored in $Guard::DIED should not die (behaviour is not guaranteed, but right now, the exception will simply be ignored). so like, don't do that. seriously. πŸ’€

πŸ‘‘ AUTHOR πŸ‘‘

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

iconic. we stan. πŸ’œ


πŸŽ€ THANKS πŸŽ€

thanks to Marco Maisenhelder, who reminded me of the $Guard::DIED solution to the problem of exceptions. king behaviour honestly. πŸ‘‘


🧚 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. typing overhead πŸ’€ imagine.
  • Hook::Scope, which has apparently never been finished and can corrupt memory when used. not the vibe. do not. πŸ™ˆ
  • Scope::Guard seems to have a big SEE ALSO section for even more modules like it. a whole friend group of modules. cute.

okay that's the whole page, bestie, you're a guard girlie now πŸ’…βœ¨

perl v5.42.2 Β· 2026-02-15 Β· that's the version and date straight off the page β€” mwah, see you in the next manpage πŸŽ€πŸ¦‹πŸ’–

πŸ“¦ where this page comes from