ViewVC Help
View File | Revision Log | Show Annotations | Download File
/cvs/Guard/README
(Generate patch)

Comparing Guard/README (file contents):
Revision 1.1 by root, Sat Dec 13 17:37:22 2008 UTC vs.
Revision 1.5 by root, Sun Jul 19 05:44:10 2009 UTC

1NAME 1NAME
2 Guard - convert between different representations of perl 2 Guard - safe cleanup blocks
3 scalars
4 3
5SYNOPSIS 4SYNOPSIS
6 use Guard; 5 use Guard;
6
7 # temporarily chdir to "/etc" directory, but make sure
8 # to go back to "/" no matter how myfun exits:
9 sub myfun {
10 scope_guard { chdir "/" };
11 chdir "/etc";
12
13 code_that_might_die_or_does_other_fun_stuff;
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
7 20
8DESCRIPTION 21DESCRIPTION
9 This module exports various internal perl methods that change the 22 This module implements so-called "guards". A guard is something (usually
10 internal representation or state of a perl scalar. All of these work 23 an object) that "guards" a resource, ensuring that it is cleaned up when
11 in-place, that is, they modify their scalar argument. No functions are 24 expected.
12 exported by default.
13 25
14 The following export tags exist: 26 Specifically, this module supports two different types of guards: guard
27 objects, which execute a given code block when destroyed, and scoped
28 guards, which are tied to the scope exit.
15 29
16 :utf8 all functions with utf8 in their name 30FUNCTIONS
17 :taint all functions with taint in their name 31 This module currently exports the "scope_guard" and "guard" functions by
18 :refcnt all functions with refcnt in their name 32 default.
19 :ok all *ok-functions.
20 33
21 utf8 scalar[, mode] 34 scope_guard BLOCK
22 Returns true when the given scalar is marked as utf8, false 35 Registers a block that is executed when the current scope (block,
23 otherwise. If the optional mode argument is given, also forces the 36 function, method, eval etc.) is exited.
24 interpretation of the string to utf8 (mode true) or plain bytes
25 (mode false). The actual (byte-) content is not changed. The return
26 value always reflects the state before any modification is done.
27 37
28 This function is useful when you "import" utf8-data into perl, or 38 See the EXCEPTIONS section for an explanation of how exceptions
29 when some external function (e.g. storing/retrieving from a 39 (i.e. "die") are handled inside guard blocks.
30 database) removes the utf8-flag.
31 40
32 utf8_on scalar 41 The description below sounds a bit complicated, but that's just
33 Similar to "utf8 scalar, 1", but additionally returns the scalar 42 because "scope_guard" tries to get even corner cases "right": the
34 (the argument is still modified in-place). 43 goal is to provide you with a rock solid clean up tool.
35 44
36 utf8_off scalar 45 The behaviour is similar to this code fragment:
37 Similar to "utf8 scalar, 0", but additionally returns the scalar
38 (the argument is still modified in-place).
39 46
40 utf8_valid scalar [Perl 5.7] 47 eval ... code following scope_guard ...
41 Returns true if the bytes inside the scalar form a valid utf8 48 {
42 string, false otherwise (the check is independent of the actual 49 local $@;
43 encoding perl thinks the string is in). 50 eval BLOCK;
51 eval { $Guard::DIED->() } if $@;
52 }
53 die if $@;
44 54
45 utf8_upgrade scalar 55 Except it is much faster, and the whole thing gets executed even
46 Convert the string content of the scalar in-place to its 56 when the BLOCK calls "exit", "goto", "last" or escapes via other
47 UTF8-encoded form (and also returns it). 57 means.
48 58
49 utf8_downgrade scalar[, fail_ok=0] 59 If multiple BLOCKs are registered to the same scope, they will be
50 Attempt to convert the string content of the scalar from 60 executed in reverse order. Other scope-related things such as
51 UTF8-encoded to ISO-8859-1. This may not be possible if the string 61 "local" are managed via the same mechanism, so variables "local"ised
52 contains characters that cannot be represented in a single byte; if 62 *after* calling "scope_guard" will be restored when the guard runs.
53 this is the case, it leaves the scalar unchanged and either returns
54 false or, if "fail_ok" is not true (the default), croaks.
55 63
56 utf8_encode scalar 64 Example: temporarily change the timezone for the current process,
57 Convert the string value of the scalar to UTF8-encoded, but then 65 ensuring it will be reset when the "if" scope is exited:
58 turn off the "SvUTF8" flag so that it looks like bytes to perl
59 again. (Might be removed in future versions).
60 66
61 utf8_length scalar 67 use Guard;
62 Returns the number of characters in the string, counting wide UTF8 68 use POSIX ();
63 characters as a single character, independent of wether the scalar
64 is marked as containing bytes or mulitbyte characters.
65 69
66 unmagic scalar, type 70 if ($need_to_switch_tz) {
67 Remove the specified magic from the scalar (DANGEROUS!). 71 # make sure we call tzset after $ENV{TZ} has been restored
72 scope_guard { POSIX::tzset };
68 73
69 weaken scalar 74 # localise after the scope_guard, so it gets undone in time
70 Weaken a reference. (See also WeakRef). 75 local $ENV{TZ} = "Europe/London";
76 POSIX::tzset;
71 77
72 taint scalar 78 # do something with the new timezone
73 Taint the scalar. 79 }
74 80
75 tainted scalar 81 my $guard = guard BLOCK
76 returns true when the scalar is tainted, false otherwise. 82 Behaves the same as "scope_guard", except that instead of executing
83 the block on scope exit, it returns an object whose lifetime
84 determines when the BLOCK gets executed: when the last reference to
85 the object gets destroyed, the BLOCK gets executed as with
86 "scope_guard".
77 87
78 untaint scalar 88 The returned object can be copied as many times as you want.
79 Remove the tainted flag from the specified scalar.
80 89
81 grow scalar, newlen 90 See the EXCEPTIONS section for an explanation of how exceptions
82 Sets the memory area used for the scalar to the given length, if the 91 (i.e. "die") are handled inside guard blocks.
83 current length is less than the new value. This does not affect the
84 contents of the scalar, but is only useful to "pre-allocate" memory
85 space if you know the scalar will grow. The return value is the
86 modified scalar (the scalar is modified in-place).
87 92
88 refcnt scalar[, newrefcnt] 93 Example: acquire a Coro::Semaphore for a second by registering a
89 Returns the current reference count of the given scalar and 94 timer. The timer callback references the guard used to unlock it
90 optionally sets it to the given reference count. 95 again. (Please ignore the fact that "Coro::Semaphore" has a "guard"
96 method that does this already):
91 97
92 refcnt_inc scalar 98 use Guard;
93 Increments the reference count of the given scalar inplace. 99 use AnyEvent;
100 use Coro::Semaphore;
94 101
95 refcnt_dec scalar 102 my $sem = new Coro::Semaphore;
96 Decrements the reference count of the given scalar inplace. Use
97 "weaken" instead if you understand what this function is fore.
98 Better yet: don't use this module in this case.
99 103
100 refcnt_rv scalar[, newrefcnt] 104 sub lock_for_a_second {
101 Works like "refcnt", but dereferences the given reference first. 105 $sem->down;
102 This is useful to find the reference count of arrays or hashes, 106 my $guard = guard { $sem->up };
103 which cnanot be passed directly. Remember that taking a reference of
104 some object increases it's reference count, so the reference count
105 used by the *_rv-functions tend to be one higher.
106 107
107 refcnt_inc_rv scalar 108 my $timer;
108 Works like "refcnt_inc", but dereferences the given reference first. 109 $timer = AnyEvent->timer (after => 1, sub {
110 # do something
111 undef $sem;
112 undef $timer;
113 });
114 }
109 115
110 refcnt_dec_rv scalar 116 The advantage of doing this with a guard instead of simply calling
111 Works like "refcnt_dec", but dereferences the given reference first. 117 "$sem->down" in the callback is that you can opt not to create the
118 timer, or your code can throw an exception before it can create the
119 timer, or you can create multiple timers or other event watchers and
120 only when the last one gets executed will the lock be unlocked.
121 Using the "guard", you do not have to worry about catching all the
122 places where you have to unlock the semaphore.
112 123
113 ok scalar 124 $guard->cancel
114 uok scalar 125 Calling this function will "disable" the guard object returned by
115 rok scalar 126 the "guard" function, i.e. it will free the BLOCK originally passed
116 pok scalar 127 to "guard "and will arrange for the BLOCK not to be executed.
117 nok scalar
118 niok scalar
119 Calls SvOK, SvUOK, SvROK, SvPOK, SvNOK or SvNIOK on the given
120 scalar, respectively.
121 128
122 CANDIDATES FOR FUTURE RELEASES 129 This can be useful when you use "guard" to create a fatal cleanup
123 The following API functions (perlapi) are considered for future 130 handler and later decide it is no longer needed.
124 inclusion in this module If you want them, write me.
125 131
126 sv_upgrade 132EXCEPTIONS
127 sv_pvn_force 133 Guard blocks should not normally throw exceptions (that is, "die").
128 sv_pvutf8n_force 134 After all, they are usually used to clean up after such exceptions.
129 the sv2xx family 135 However, if something truly exceptional is happening, a guard block
136 should be allowed to die. Also, programming errors are a large source of
137 exceptions, and the programmer certainly wants to know about those.
138
139 Since in most cases, the block executing when the guard gets executed
140 does not know or does not care about the guard blocks, it makes little
141 sense to let containing code handle the exception.
142
143 Therefore, whenever a guard block throws an exception, it will be
144 caught, followed by calling the code reference stored in $Guard::DIED
145 (with $@ set to the actual exception), which is similar to how most
146 event loops handle this case.
147
148 The default for $Guard::DIED is to call "warn "$@"".
149
150 The $@ variable will be restored to its value before the guard call in
151 all cases, so guards will not disturb $@ in any way.
152
153 The code reference stored in $Guard::DIED should not die (behaviour is
154 not guaranteed, but right now, the exception will simply be ignored).
130 155
131AUTHOR 156AUTHOR
132 Marc Lehmann <schmorp@schmorp.de> 157 Marc Lehmann <schmorp@schmorp.de>
133 http://home.schmorp.de/ 158 http://home.schmorp.de/
134 159
160THANKS
161 Thanks to Marco Maisenhelder, who reminded me of the $Guard::DIED
162 solution to the problem of exceptions.
163
164SEE ALSO
165 Scope::Guard and Sub::ScopeFinalizer, which actually implement dynamic,
166 not scoped guards, and have a lot higher CPU, memory and typing
167 overhead.
168
169 Hook::Scope, which has apparently never been finished and corrupts
170 memory when used.
171

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines