]> git.vpit.fr Git - perl/modules/Variable-Magic.git/blob - README
This is 0.30
[perl/modules/Variable-Magic.git] / README
1 NAME
2     Variable::Magic - Associate user-defined magic to variables from Perl.
3
4 VERSION
5     Version 0.30
6
7 SYNOPSIS
8         use Variable::Magic qw/wizard cast dispell/;
9
10         my $wiz = wizard set => sub { print STDERR "now set to ${$_[0]}!\n" };
11         my $a = 1;
12         cast $a, $wiz;
13         $a = 2;          # "now set to 2!"
14         dispell $a, $wiz;
15         $a = 3           # (nothing)
16
17 DESCRIPTION
18     Magic is Perl way of enhancing objects. This mechanism let the user add
19     extra data to any variable and hook syntaxical operations (such as
20     access, assignation or destruction) that can be applied to it. With this
21     module, you can add your own magic to any variable without the pain of
22     the C API.
23
24     Magic differs from tieing and overloading in several ways :
25
26     *   Magic isn't copied on assignation (as for blessed references) : you
27         attach it to variables, not values.
28
29     *   It doesn't replace the original semantics : magic callbacks trigger
30         before the original action take place, and can't prevent it to
31         happen.
32
33     *   It's mostly invisible at the Perl level : magical and non-magical
34         variables cannot be distinguished with "ref", "reftype" or another
35         trick.
36
37     *   It's notably faster, since perl's way of handling magic is lighter
38         by nature, and there's no need for any method resolution.
39
40     The operations that can be overloaded are :
41
42     *   "get"
43
44         This magic is invoked when the variable is evaluated (does not
45         include array/hash subscripts and slices).
46
47     *   "set"
48
49         This one is triggered each time the value of the variable changes
50         (includes array/hash subscripts and slices).
51
52     *   "len"
53
54         This magic is a little special : it is called when the 'size' or the
55         'length' of the variable has to be known by Perl. Typically, it's
56         the magic involved when an array is evaluated in scalar context, but
57         also on array assignation and loops ("for", "map" or "grep"). The
58         callback has then to return the length as an integer.
59
60     *   "clear"
61
62         This magic is invoked when the variable is reset, such as when an
63         array is emptied. Please note that this is different from undefining
64         the variable, even though the magic is called when the clearing is a
65         result of the undefine (e.g. for an array, but actually a bug
66         prevent it to work before perl 5.9.5 - see the history).
67
68     *   "free"
69
70         This one can be considered as an object destructor. It happens when
71         the variable goes out of scope (with the exception of global scope),
72         but not when it is undefined.
73
74     *   "copy"
75
76         This magic only applies to tied arrays and hashes. It fires when you
77         try to access or change their elements. It is available on your perl
78         iff "MGf_COPY" is true.
79
80     *   "dup"
81
82         Invoked when the variable is cloned across threads. Currently not
83         available.
84
85     *   "local"
86
87         When this magic is set on a variable, all subsequent localizations
88         of the variable will trigger the callback. It is available on your
89         perl iff "MGf_LOCAL" is true.
90
91     The following actions only apply to hashes and are available iff
92     "VMG_UVAR" is true. They are referred to as "uvar" magics.
93
94     *   "fetch"
95
96         This magic happens each time an element is fetched from the hash.
97
98     *   "store"
99
100         This one is called when an element is stored into the hash.
101
102     *   "exists"
103
104         This magic fires when a key is tested for existence in the hash.
105
106     *   "delete"
107
108         This last one triggers when a key is deleted in the hash, regardless
109         of whether the key actually exists in it.
110
111     You can refer to the tests to have more insight of where the different
112     magics are invoked.
113
114     To prevent any clash between different magics defined with this module,
115     an unique numerical signature is attached to each kind of magic (i.e.
116     each set of callbacks for magic operations).
117
118 PERL MAGIC HISTORY
119     The places where magic is invoked have changed a bit through perl
120     history. Here's a little list of the most recent ones.
121
122     *   5.6.x
123
124         *p14416* : 'copy' and 'dup' magic.
125
126     *   5.8.9
127
128         *p28160* : Integration of *p25854* (see below).
129
130         *p32542* : Integration of *p31473* (see below).
131
132     *   5.9.3
133
134         *p25854* : 'len' magic is no longer called when pushing an element
135         into a magic array.
136
137         *p26569* : 'local' magic.
138
139     *   5.9.5
140
141         *p31064* : Meaningful 'uvar' magic.
142
143         *p31473* : 'clear' magic wasn't invoked when undefining an array.
144         The bug is fixed as of this version.
145
146     *   5.10.0
147
148         Since "PERL_MAGIC_uvar" is uppercased, "hv_magic_check()" triggers
149         'copy' magic on hash stores for (non-tied) hashes that also have
150         'uvar' magic.
151
152     *   5.11.x
153
154         *p32969* : 'len' magic is no longer invoked when calling "length"
155         with a magical scalar.
156
157         *p34908* : 'len' magic is no longer called when pushing / unshifting
158         an element into a magical array in void context. The "push" part was
159         already covered by *p25854*.
160
161 CONSTANTS
162   "SIG_MIN"
163     The minimum integer used as a signature for user-defined magic.
164
165   "SIG_MAX"
166     The maximum integer used as a signature for user-defined magic.
167
168   "SIG_NBR"
169         SIG_NBR = SIG_MAX - SIG_MIN + 1
170
171   "MGf_COPY"
172     Evaluates to true iff the 'copy' magic is available.
173
174   "MGf_DUP"
175     Evaluates to true iff the 'dup' magic is available.
176
177   "MGf_LOCAL"
178     Evaluates to true iff the 'local' magic is available.
179
180   "VMG_UVAR"
181     When this constant is true, you can use the "fetch,store,exists,delete"
182     callbacks on hashes.
183
184   "VMG_COMPAT_ARRAY_PUSH_NOLEN"
185     True for perls that don't call 'len' magic when you push an element in a
186     magical array.
187
188   "VMG_COMPAT_ARRAY_UNSHIFT_NOLEN_VOID"
189     True for perls that don't call 'len' magic when you unshift in void
190     context an element in a magical array.
191
192   "VMG_COMPAT_ARRAY_UNDEF_CLEAR"
193     True for perls that call 'clear' magic when undefining magical arrays.
194
195   "VMG_COMPAT_SCALAR_LENGTH_NOLEN"
196     True for perls that don't call 'len' magic when taking the "length" of a
197     magical scalar.
198
199   "VMG_PERL_PATCHLEVEL"
200     The perl patchlevel this module was built with, or 0 for non-debugging
201     perls.
202
203   "VMG_THREADSAFE"
204     True iff this module could have been built with thread-safety features
205     enabled.
206
207   "VMG_OP_INFO_NAME"
208     Value to pass with "op_info" to get the current op name in the magic
209     callbacks.
210
211   "VMG_OP_INFO_OBJECT"
212     Value to pass with "op_info" to get a "B::OP" object representing the
213     current op in the magic callbacks.
214
215 FUNCTIONS
216   "wizard"
217         wizard sig      => ...,
218                data     => sub { ... },
219                get      => sub { my ($ref, $data [, $op]) = @_; ... },
220                set      => sub { my ($ref, $data [, $op]) = @_; ... },
221                len      => sub { my ($ref, $data, $len [, $op]) = @_; ... ; return $newlen; },
222                clear    => sub { my ($ref, $data [, $op]) = @_; ... },
223                free     => sub { my ($ref, $data [, $op]) = @_, ... },
224                copy     => sub { my ($ref, $data, $key, $elt [, $op]) = @_; ... },
225                local    => sub { my ($ref, $data [, $op]) = @_; ... },
226                fetch    => sub { my ($ref, $data, $key [, $op]) = @_; ... },
227                store    => sub { my ($ref, $data, $key [, $op]) = @_; ... },
228                exists   => sub { my ($ref, $data, $key [, $op]) = @_; ... },
229                delete   => sub { my ($ref, $data, $key [, $op]) = @_; ... },
230                copy_key => $bool,
231                op_info  => [ 0 | VMG_OP_INFO_NAME | VMG_OP_INFO_OBJECT ]
232
233     This function creates a 'wizard', an opaque type that holds the magic
234     information. It takes a list of keys / values as argument, whose keys
235     can be :
236
237     *   "sig"
238
239         The numerical signature. If not specified or undefined, a random
240         signature is generated. If the signature matches an already defined
241         magic, then the existant magic object is returned.
242
243     *   "data"
244
245         A code reference to a private data constructor. It is called each
246         time this magic is cast on a variable, and the scalar returned is
247         used as private data storage for it. $_[0] is a reference to the
248         magic object and @_[1 .. @_-1] are all extra arguments that were
249         passed to "cast".
250
251     *   "get", "set", "len", "clear", "free", "copy", "local", "fetch",
252         "store", "exists" and "delete"
253
254         Code references to the corresponding magic callbacks. You don't have
255         to specify all of them : the magic associated with undefined entries
256         simply won't be hooked. In those callbacks, $_[0] is always a
257         reference to the magic object and $_[1] is always the private data
258         (or "undef" when no private data constructor was supplied).
259
260         Moreover, when you pass "op_info => $num" to "wizard", the last
261         element of @_ will be the current op name if "$num ==
262         VMG_OP_INFO_NAME" and a "B::OP" object representing the current op
263         if "$num == VMG_OP_INFO_OBJECT". Both have a performance hit, but
264         just getting the name is lighter than getting the op object.
265
266         Other arguments are specific to the magic hooked :
267
268         *       "len"
269
270                 When the variable is an array or a scalar, $_[2] contains
271                 the non-magical length. The callback can return the new
272                 scalar or array length to use, or "undef" to default to the
273                 normal length.
274
275         *       "copy"
276
277                 $_[2] is a either a copy or an alias of the current key,
278                 which means that it is useless to try to change or cast
279                 magic on it. $_[3] is an alias to the current element (i.e.
280                 the value).
281
282         *       "fetch", "store", "exists" and "delete"
283
284                 $_[2] is an alias to the current key. Nothing prevents you
285                 from changing it, but be aware that there lurk dangerous
286                 side effects. For example, it may righteously be readonly if
287                 the key was a bareword. You can get a copy instead by
288                 passing "copy_key => 1" to "wizard", which allows you to
289                 safely assign to $_[2] in order to e.g. redirect the action
290                 to another key. This however has a little performance
291                 drawback because of the copy.
292
293         All the callbacks are expected to return an integer, which is passed
294         straight to the perl magic API. However, only the return value of
295         the "len" callback currently holds a meaning.
296
297         # A simple scalar tracer
298         my $wiz = wizard get  => sub { print STDERR "got ${$_[0]}\n" },
299                          set  => sub { print STDERR "set to ${$_[0]}\n" },
300                          free => sub { print STDERR "${$_[0]} was deleted\n" }
301
302   "gensig"
303     With this tool, you can manually generate random magic signature between
304     SIG_MIN and SIG_MAX inclusive. That's the way "wizard" creates them when
305     no signature is supplied.
306
307         # Generate a signature
308         my $sig = gensig;
309
310   "getsig"
311         getsig $wiz
312
313     This accessor returns the magic signature of this wizard.
314
315         # Get $wiz signature
316         my $sig = getsig $wiz;
317
318   "cast"
319         cast [$@%&*]var, [$wiz|$sig], ...
320
321     This function associates $wiz magic to the variable supplied, without
322     overwriting any other kind of magic. You can also supply the numeric
323     signature $sig instead of $wiz. It returns true on success or when $wiz
324     magic is already present, 0 on error, and "undef" when no magic
325     corresponds to the given signature (in case $sig was supplied). All
326     extra arguments specified after $wiz are passed to the private data
327     constructor. If the variable isn't a hash, any "uvar" callback of the
328     wizard is safely ignored.
329
330         # Casts $wiz onto $x. If $wiz isn't a signature, undef can't be returned.
331         my $x;
332         die 'error' unless cast $x, $wiz;
333
334     The "var" argument can be an array or hash value. Magic for those
335     behaves like for any other scalar, except that it is dispelled when the
336     entry is deleted from the container. For example, if you want to call
337     "POSIX::tzset" each time the 'TZ' environment variable is changed in
338     %ENV, you can use :
339
340         use POSIX;
341         cast $ENV{TZ}, wizard set => sub { POSIX::tzset(); () };
342
343     If you want to overcome the possible deletion of the 'TZ' entry, you
344     have no choice but to rely on "store" uvar magic.
345
346   "getdata"
347         getdata [$@%&*]var, [$wiz|$sig]
348
349     This accessor fetches the private data associated with the magic $wiz
350     (or the signature $sig) in the variable. "undef" is returned when no
351     such magic or data is found, or when $sig does not represent a current
352     valid magic object.
353
354         # Get the attached data.
355         my $data = getdata $x, $wiz or die 'no such magic or magic has no data';
356
357   "dispell"
358         dispell [$@%&*]variable, [$wiz|$sig]
359
360     The exact opposite of "cast" : it dissociates $wiz magic from the
361     variable. You can also pass the magic signature $sig as the second
362     argument. True is returned on success, 0 on error or when no magic
363     represented by $wiz could be found in the variable, and "undef" when no
364     magic corresponds to the given signature (in case $sig was supplied).
365
366         # Dispell now. If $wiz isn't a signature, undef can't be returned.
367         die 'no such magic or error' unless dispell $x, $wiz;
368
369 EXPORT
370     The functions "wizard", "gensig", "getsig", "cast", "getdata" and
371     "dispell" are only exported on request. All of them are exported by the
372     tags ':funcs' and ':all'.
373
374     The constants "SIG_MIN", "SIG_MAX", "SIG_NBR", "MGf_COPY", "MGf_DUP",
375     "MGf_LOCAL" and "VMG_UVAR" are also only exported on request. They are
376     all exported by the tags ':consts' and ':all'.
377
378 CAVEATS
379     If you store a magic object in the private data slot, the magic won't be
380     accessible by "getdata" since it's not copied by assignation. The only
381     way to address this would be to return a reference.
382
383     If you define a wizard with a "free" callback and cast it on itself,
384     this destructor won't be called because the wizard will be destroyed
385     first.
386
387 DEPENDENCIES
388     perl 5.8.
389
390     Carp (standard since perl 5), XSLoader (standard since perl 5.006).
391
392     Copy tests need Tie::Array (standard since perl 5.005) and Tie::Hash
393     (since 5.002).
394
395     Some uvar tests need Hash::Util::FieldHash (standard since perl
396     5.009004).
397
398     Glob tests need Symbol (standard since perl 5.002).
399
400     Threads tests need threads and threads::shared.
401
402 SEE ALSO
403     perlguts and perlapi for internal information about magic.
404
405     perltie and overload for other ways of enhancing objects.
406
407 AUTHOR
408     Vincent Pit, "<perl at profvince.com>", <http://www.profvince.com>.
409
410     You can contact me by mail or on "irc.perl.org" (vincent).
411
412 BUGS
413     Please report any bugs or feature requests to "bug-variable-magic at
414     rt.cpan.org", or through the web interface at
415     <http://rt.cpan.org/NoAuth/ReportBug.html?Queue=Variable-Magic>. I will
416     be notified, and then you'll automatically be notified of progress on
417     your bug as I make changes.
418
419 SUPPORT
420     You can find documentation for this module with the perldoc command.
421
422         perldoc Variable::Magic
423
424     Tests code coverage report is available at
425     <http://www.profvince.com/perl/cover/Variable-Magic>.
426
427 COPYRIGHT & LICENSE
428     Copyright 2007-2009 Vincent Pit, all rights reserved.
429
430     This program is free software; you can redistribute it and/or modify it
431     under the same terms as Perl itself.
432