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