… | |
… | |
2 | |
2 | |
3 | Guard - safe cleanup blocks |
3 | Guard - safe cleanup blocks |
4 | |
4 | |
5 | =head1 SYNOPSIS |
5 | =head1 SYNOPSIS |
6 | |
6 | |
7 | use Guard; |
7 | use Guard; |
8 | |
8 | |
9 | # temporarily chdir to "/etc" directory, but make sure |
9 | # temporarily chdir to "/etc" directory, but make sure |
10 | # to go back to "/" no matter how myfun exits: |
10 | # to go back to "/" no matter how myfun exits: |
11 | sub myfun { |
11 | sub myfun { |
12 | scope_guard { chdir "/" }; |
12 | scope_guard { chdir "/" }; |
13 | chdir "/etc"; |
13 | chdir "/etc"; |
14 | |
14 | |
15 | call_function_that_might_die_or_other_fun_stuff; |
15 | call_function_that_might_die_or_other_fun_stuff; |
16 | } |
16 | } |
17 | |
17 | |
18 | =head1 DESCRIPTION |
18 | =head1 DESCRIPTION |
19 | |
19 | |
20 | This module implements so-called "guards". A guard is something (usually |
20 | This module implements so-called "guards". A guard is something (usually |
21 | an object) that "guards" a resource, ensuring that it is cleaned up when |
21 | an object) that "guards" a resource, ensuring that it is cleaned up when |
… | |
… | |
109 | (i.e. C<die>) are handled inside guard blocks. |
109 | (i.e. C<die>) are handled inside guard blocks. |
110 | |
110 | |
111 | Example: acquire a Coro::Semaphore for a second by registering a |
111 | Example: acquire a Coro::Semaphore for a second by registering a |
112 | timer. The timer callback references the guard used to unlock it again. |
112 | timer. The timer callback references the guard used to unlock it again. |
113 | |
113 | |
|
|
114 | use Guard; |
114 | use AnyEvent; |
115 | use AnyEvent; |
115 | use Coro::Semaphore; |
116 | use Coro::Semaphore; |
116 | |
117 | |
117 | my $sem = new Coro::Semaphore; |
118 | my $sem = new Coro::Semaphore; |
118 | |
119 | |
119 | sub lock_1s { |
120 | sub lock_for_a_second { |
120 | $sem->down; |
121 | $sem->down; |
121 | my $guard = guard { $sem->up }; |
122 | my $guard = guard { $sem->up }; |
122 | |
123 | |
123 | my $timer; |
124 | my $timer; |
124 | $timer = AnyEvent->timer (after => 1, sub { |
125 | $timer = AnyEvent->timer (after => 1, sub { |