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