```{index} single: Guard ``` # Guard ```{pperl-module-badges} Guard ``` `Guard` - run a piece of code when a scope ends or an object goes away. ```perl use Guard; { scope_guard { print "leaving the block\n" }; ... } # prints here, however the block is left my $g = guard { unlink $tempfile }; ... undef $g; # runs now - or whenever the last copy goes ``` `scope_guard BLOCK` runs the block when the enclosing scope is left: at its end, through `return`, `last`, or an exception unwinding past it. `guard BLOCK` returns an object that runs the block when it is destroyed - when the last reference to it goes away. It can be stored, passed around and kept in a data structure, and the code runs exactly once, when nothing holds it any more. `Guard::cancel($guard)` disarms one: its code will then never run. The code runs with `$@` saved and restored, so a guard firing while an exception is on its way out does not overwrite it. If the guard's own code dies, the exception is handed to `$Guard::DIED`, which by default `warn`s it; the exception never escapes the guard. This is a native implementation of the CPAN module Guard 1.023; its `Guard.pm` is used unchanged. ## Differences from upstream One, where perl 5.44 with Guard.xs fails: `Guard::cancel(\1)` - a reference to a plain number or undef - dies "Guard::cancel called on a non-guard object", as for every other non-guard; perl5 reads past the value and crashes some of the time (t/81-xs-native/Guard/300-guard-surface.t). ## Functions ### Other Functions #### [`scope_guard`](Guard/scope_guard) `scope_guard BLOCK`: run BLOCK when the enclosing scope is left - at its end, by `return`, `last`/`next`, or an exception passing through. Several in one scope run in reverse order of creation. Exported by default. #### `guard` `guard BLOCK`: an object that runs BLOCK when it is destroyed, that is when the last reference to it goes away - so the code's lifetime can be tied to a data structure rather than a scope. Exported by default. #### `cancel` `Guard::cancel($guard)`: disarm a guard object made by `guard` - its code will never run. Anything else dies "Guard::cancel called on a non-guard object". Not exported; it is also the method `$guard->cancel`. ```{toctree} :hidden: :maxdepth: 1 Guard/scope_guard ```