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.6 by root, Fri Mar 12 17:25:58 2010 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 See the EXCEPTIONS section for an explanation of how exceptions
79 Remove the tainted flag from the specified scalar. 89 (i.e. "die") are handled inside guard blocks.
80 90
81 grow scalar, newlen 91 Example: acquire a Coro::Semaphore for a second by registering a
82 Sets the memory area used for the scalar to the given length, if the 92 timer. The timer callback references the guard used to unlock it
83 current length is less than the new value. This does not affect the 93 again. (Please ignore the fact that "Coro::Semaphore" has a "guard"
84 contents of the scalar, but is only useful to "pre-allocate" memory 94 method that does this already):
85 space if you know the scalar will grow. The return value is the
86 modified scalar (the scalar is modified in-place).
87 95
88 refcnt scalar[, newrefcnt] 96 use Guard;
89 Returns the current reference count of the given scalar and 97 use Coro::AnyEvent;
90 optionally sets it to the given reference count. 98 use Coro::Semaphore;
91 99
92 refcnt_inc scalar 100 my $sem = new Coro::Semaphore;
93 Increments the reference count of the given scalar inplace.
94 101
95 refcnt_dec scalar 102 sub lock_for_a_second {
96 Decrements the reference count of the given scalar inplace. Use 103 $sem->down;
97 "weaken" instead if you understand what this function is fore. 104 my $guard = guard { $sem->up };
98 Better yet: don't use this module in this case.
99 105
100 refcnt_rv scalar[, newrefcnt] 106 Coro::AnyEvent::sleep 1;
101 Works like "refcnt", but dereferences the given reference first.
102 This is useful to find the reference count of arrays or hashes,
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 # $sem->up gets executed when returning
108 Works like "refcnt_inc", but dereferences the given reference first. 109 }
109 110
110 refcnt_dec_rv scalar 111 The advantage of doing this with a guard instead of simply calling
111 Works like "refcnt_dec", but dereferences the given reference first. 112 "$sem->down" in the callback is that you can opt not to create the
113 timer, or your code can throw an exception before it can create the
114 timer (or the thread gets canceled), or you can create multiple
115 timers or other event watchers and only when the last one gets
116 executed will the lock be unlocked. Using the "guard", you do not
117 have to worry about catching all the places where you have to unlock
118 the semaphore.
112 119
113 ok scalar 120 $guard->cancel
114 uok scalar 121 Calling this function will "disable" the guard object returned by
115 rok scalar 122 the "guard" function, i.e. it will free the BLOCK originally passed
116 pok scalar 123 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 124
122 CANDIDATES FOR FUTURE RELEASES 125 This can be useful when you use "guard" to create a cleanup handler
123 The following API functions (perlapi) are considered for future 126 to be called under fatal conditions and later decide it is no longer
124 inclusion in this module If you want them, write me. 127 needed.
125 128
126 sv_upgrade 129EXCEPTIONS
127 sv_pvn_force 130 Guard blocks should not normally throw exceptions (that is, "die").
128 sv_pvutf8n_force 131 After all, they are usually used to clean up after such exceptions.
129 the sv2xx family 132 However, if something truly exceptional is happening, a guard block
133 should of course be allowed to die. Also, programming errors are a large
134 source of exceptions, and the programmer certainly wants to know about
135 those.
136
137 Since in most cases, the block executing when the guard gets executed
138 does not know or does not care about the guard blocks, it makes little
139 sense to let containing code handle the exception.
140
141 Therefore, whenever a guard block throws an exception, it will be caught
142 by Guard, followed by calling the code reference stored in $Guard::DIED
143 (with $@ set to the actual exception), which is similar to how most
144 event loops handle this case.
145
146 The default for $Guard::DIED is to call "warn "$@"", i.e. the error is
147 printed as a warning and the program continues.
148
149 The $@ variable will be restored to its value before the guard call in
150 all cases, so guards will not disturb $@ in any way.
151
152 The code reference stored in $Guard::DIED should not die (behaviour is
153 not guaranteed, but right now, the exception will simply be ignored).
130 154
131AUTHOR 155AUTHOR
132 Marc Lehmann <schmorp@schmorp.de> 156 Marc Lehmann <schmorp@schmorp.de>
133 http://home.schmorp.de/ 157 http://home.schmorp.de/
134 158
159THANKS
160 Thanks to Marco Maisenhelder, who reminded me of the $Guard::DIED
161 solution to the problem of exceptions.
162
163SEE ALSO
164 Scope::Guard and Sub::ScopeFinalizer, which actually implement dynamic
165 guards only, not scoped guards, and have a lot higher CPU, memory and
166 typing overhead.
167
168 Hook::Scope, which has apparently never been finished and can corrupt
169 memory when used.
170

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines