1 | NAME |
1 | NAME |
2 | Guard - safe cleanup blocks |
2 | Guard - safe cleanup blocks |
3 | |
3 | |
4 | SYNOPSIS |
4 | SYNOPSIS |
5 | use Guard; |
5 | use Guard; |
6 | |
6 | |
7 | # temporarily chdir to "/etc" directory, but make sure |
7 | # temporarily chdir to "/etc" directory, but make sure |
8 | # to go back to "/" no matter how myfun exits: |
8 | # to go back to "/" no matter how myfun exits: |
9 | sub myfun { |
9 | sub myfun { |
10 | scope_guard { chdir "/" }; |
10 | scope_guard { chdir "/" }; |
11 | chdir "/etc"; |
11 | chdir "/etc"; |
12 | |
12 | |
13 | code_that_might_die_or_does_other_fun_stuff; |
13 | code_that_might_die_or_does_other_fun_stuff; |
14 | } |
14 | } |
|
|
15 | |
|
|
16 | # create an object that, when the last reference to it is gone, |
|
|
17 | # invokes the given codeblock: |
|
|
18 | my $guard = guard { print "destroyed!\n" }; |
|
|
19 | undef $guard; # probably destroyed here |
15 | |
20 | |
16 | DESCRIPTION |
21 | DESCRIPTION |
17 | This module implements so-called "guards". A guard is something (usually |
22 | This module implements so-called "guards". A guard is something (usually |
18 | an object) that "guards" a resource, ensuring that it is cleaned up when |
23 | an object) that "guards" a resource, ensuring that it is cleaned up when |
19 | expected. |
24 | expected. |