]> git.vpit.fr Git - perl/modules/Variable-Magic.git/blob - README
This is 0.38
[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.38
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 usually trigger before the original action take
56         place, and can't prevent it to happen. This also makes catching
57         individual events easier than with "tie", where you have to provide
58         fallbacks methods for all actions by usually inheriting from the
59         correct "Tie::Std*" class and overriding individual methods in your
60         own class.
61
62     *   It's type-agnostic.
63
64         The same magic can be applied on scalars, arrays, hashes, subs or
65         globs. But the same hook (see below for a list) may trigger
66         differently depending on the the type of the variable.
67
68     *   It's mostly invisible at the Perl level.
69
70         Magical and non-magical variables cannot be distinguished with
71         "ref", "tied" or another trick.
72
73     *   It's notably faster.
74
75         Mainly because perl's way of handling magic is lighter by nature,
76         and because there's no need for any method resolution. Also, since
77         you don't have to reimplement all the variable semantics, you only
78         pay for what you actually use.
79
80     The operations that can be overloaded are :
81
82     *   "get"
83
84         This magic is invoked when the variable is evaluated. It is never
85         called for arrays and hashes.
86
87     *   "set"
88
89         This one is triggered each time the value of the variable changes.
90         It is called for array subscripts and slices, but never for hashes.
91
92     *   "len"
93
94         This magic is a little special : it is called when the 'size' or the
95         'length' of the variable has to be known by Perl. Typically, it's
96         the magic involved when an array is evaluated in scalar context, but
97         also on array assignment and loops ("for", "map" or "grep"). The
98         callback has then to return the length as an integer.
99
100     *   "clear"
101
102         This magic is invoked when the variable is reset, such as when an
103         array is emptied. Please note that this is different from undefining
104         the variable, even though the magic is called when the clearing is a
105         result of the undefine (e.g. for an array, but actually a bug
106         prevent it to work before perl 5.9.5 - see the 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, but not when it is undefined.
112
113     *   "copy"
114
115         This magic only applies to tied arrays and hashes. It fires when you
116         try to access or change their elements. It is available on your perl
117         iff "MGf_COPY" is true.
118
119     *   "dup"
120
121         Invoked when the variable is cloned across threads. Currently not
122         available.
123
124     *   "local"
125
126         When this magic is set on a variable, all subsequent localizations
127         of the variable will trigger the callback. It is available on your
128         perl iff "MGf_LOCAL" is true.
129
130     The following actions only apply to hashes and are available iff
131     "VMG_UVAR" is true. They are referred to as "uvar" magics.
132
133     *   "fetch"
134
135         This magic happens each time an element is fetched from the hash.
136
137     *   "store"
138
139         This one is called when an element is stored into the hash.
140
141     *   "exists"
142
143         This magic fires when a key is tested for existence in the hash.
144
145     *   "delete"
146
147         This last one triggers when a key is deleted in the hash, regardless
148         of whether the key actually exists in it.
149
150     You can refer to the tests to have more insight of where the different
151     magics are invoked.
152
153     To prevent any clash between different magics defined with this module,
154     an unique numerical signature is attached to each kind of magic (i.e.
155     each set of callbacks for magic operations). At the C level, magic
156     tokens owned by magic created by this module have their "mg->mg_private"
157     field set to 0x3891 or 0x3892, so please don't use these magic (sic)
158     numbers in other extensions.
159
160 FUNCTIONS
161   "wizard"
162         wizard data     => sub { ... },
163                get      => sub { my ($ref, $data [, $op]) = @_; ... },
164                set      => sub { my ($ref, $data [, $op]) = @_; ... },
165                len      => sub { my ($ref, $data, $len [, $op]) = @_; ... ; return $newlen; },
166                clear    => sub { my ($ref, $data [, $op]) = @_; ... },
167                free     => sub { my ($ref, $data [, $op]) = @_, ... },
168                copy     => sub { my ($ref, $data, $key, $elt [, $op]) = @_; ... },
169                local    => sub { my ($ref, $data [, $op]) = @_; ... },
170                fetch    => sub { my ($ref, $data, $key [, $op]) = @_; ... },
171                store    => sub { my ($ref, $data, $key [, $op]) = @_; ... },
172                exists   => sub { my ($ref, $data, $key [, $op]) = @_; ... },
173                delete   => sub { my ($ref, $data, $key [, $op]) = @_; ... },
174                copy_key => $bool,
175                op_info  => [ 0 | VMG_OP_INFO_NAME | VMG_OP_INFO_OBJECT ]
176
177     This function creates a 'wizard', an opaque type that holds the magic
178     information. It takes a list of keys / values as argument, whose keys
179     can be :
180
181     *   "sig"
182
183         The numerical signature. If not specified or undefined, a random
184         signature is generated. If the signature matches an already defined
185         magic, then the existant magic object is returned.
186
187         This option is deprecated and will be removed in december 2009.
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 rightfully 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     This function is deprecated and will be removed in december 2009.
261
262   "getsig"
263         getsig $wiz
264
265     This accessor returns the magic signature of this wizard.
266
267         # Get $wiz signature
268         my $sig = getsig $wiz;
269
270     This function is deprecated and will be removed in december 2009.
271
272   "cast"
273         cast [$@%&*]var, $wiz, ...
274
275     This function associates $wiz magic to the variable supplied, without
276     overwriting any other kind of magic. It returns true on success or when
277     $wiz magic is already present, and croaks on error. All extra arguments
278     specified after $wiz are passed to the private data constructor in @_[1
279     .. @_-1]. If the variable isn't a hash, any "uvar" callback of the
280     wizard is safely ignored.
281
282         # Casts $wiz onto $x, and pass '1' to the data constructor.
283         my $x;
284         cast $x, $wiz, 1;
285
286     The "var" argument can be an array or hash value. Magic for those
287     behaves like for any other scalar, except that it is dispelled when the
288     entry is deleted from the container. For example, if you want to call
289     "POSIX::tzset" each time the 'TZ' environment variable is changed in
290     %ENV, you can use :
291
292         use POSIX;
293         cast $ENV{TZ}, wizard set => sub { POSIX::tzset(); () };
294
295     If you want to overcome the possible deletion of the 'TZ' entry, you
296     have no choice but to rely on "store" uvar magic.
297
298   "getdata"
299         getdata [$@%&*]var, $wiz
300
301     This accessor fetches the private data associated with the magic $wiz in
302     the variable. It croaks when $wiz do not represent a valid magic object,
303     and returns an empty list if no such magic is attached to the variable
304     or when the wizard has no data constructor.
305
306         # Get the attached data, or undef if the wizard does not attach any.
307         my $data = getdata $x, $wiz;
308
309   "dispell"
310         dispell [$@%&*]variable, $wiz
311
312     The exact opposite of "cast" : it dissociates $wiz magic from the
313     variable. This function returns true on success, 0 when no magic
314     represented by $wiz could be found in the variable, and croaks if the
315     supplied wizard is invalid.
316
317         # Dispell now.
318         die 'no such magic in $x' unless dispell $x, $wiz;
319
320 CONSTANTS
321   "SIG_MIN"
322     The minimum integer used as a signature for user-defined magic.
323
324     This constant is deprecated and will be removed in december 2009.
325
326   "SIG_MAX"
327     The maximum integer used as a signature for user-defined magic.
328
329     This constant is deprecated and will be removed in december 2009.
330
331   "SIG_NBR"
332         SIG_NBR = SIG_MAX - SIG_MIN + 1
333
334     This constant is deprecated and will be removed in december 2009.
335
336   "MGf_COPY"
337     Evaluates to true iff the 'copy' magic is available.
338
339   "MGf_DUP"
340     Evaluates to true iff the 'dup' magic is available.
341
342   "MGf_LOCAL"
343     Evaluates to true iff the 'local' magic is available.
344
345   "VMG_UVAR"
346     When this constant is true, you can use the "fetch,store,exists,delete"
347     callbacks on hashes.
348
349   "VMG_COMPAT_ARRAY_PUSH_NOLEN"
350     True for perls that don't call 'len' magic when you push an element in a
351     magical array. Starting from perl 5.11.0, this only refers to pushes in
352     non-void context and hence is false.
353
354   "VMG_COMPAT_ARRAY_PUSH_NOLEN_VOID"
355     True for perls that don't call 'len' magic when you push in void context
356     an element in a magical array.
357
358   "VMG_COMPAT_ARRAY_UNSHIFT_NOLEN_VOID"
359     True for perls that don't call 'len' magic when you unshift in void
360     context an element in a magical array.
361
362   "VMG_COMPAT_ARRAY_UNDEF_CLEAR"
363     True for perls that call 'clear' magic when undefining magical arrays.
364
365   "VMG_COMPAT_SCALAR_LENGTH_NOLEN"
366     True for perls that don't call 'len' magic when taking the "length" of a
367     magical scalar.
368
369   "VMG_PERL_PATCHLEVEL"
370     The perl patchlevel this module was built with, or 0 for non-debugging
371     perls.
372
373   "VMG_THREADSAFE"
374     True iff this module could have been built with thread-safety features
375     enabled.
376
377   "VMG_FORKSAFE"
378     True iff this module could have been built with fork-safety features
379     enabled. This will always be true except on Windows where it's false for
380     perl 5.10.0 and below .
381
382   "VMG_OP_INFO_NAME"
383     Value to pass with "op_info" to get the current op name in the magic
384     callbacks.
385
386   "VMG_OP_INFO_OBJECT"
387     Value to pass with "op_info" to get a "B::OP" object representing the
388     current op in the magic callbacks.
389
390 COOKBOOK
391   Associate an object to any perl variable
392     This can be useful for passing user data through limited APIs.
393
394         {
395          package Magical::UserData;
396
397          use Variable::Magic qw/wizard cast getdata/;
398
399          my $wiz = wizard data => sub { \$_[1] };
400
401          sub ud (\[$@%*&]) : lvalue {
402           my ($var) = @_;
403           my $data = &getdata($var, $wiz);
404           unless (defined $data) {
405            &cast($var, $wiz);
406            $data = &getdata($var, $wiz);
407            die "Couldn't cast UserData magic onto the variable" unless defined $data;
408           }
409           $$data;
410          }
411         }
412
413         {
414          BEGIN { *ud = \&Magical::UserData::ud }
415
416          my $cb;
417          $cb = sub { print 'Hello, ', ud(&$cb), "!\n" };
418
419          ud(&$cb) = 'world';
420          $cb->(); # Hello, world!
421         }
422
423   Recursively cast magic on datastructures
424     "cast" can be called from any magical callback, and in particular from
425     "data". This allows you to recursively cast magic on datastructures :
426
427         my $wiz;
428         $wiz = wizard data => sub {
429          my ($var, $depth) = @_;
430          $depth ||= 0;
431          my $r = ref $var;
432          if ($r eq 'ARRAY') {
433           &cast((ref() ? $_ : \$_), $wiz, $depth + 1) for @$var;
434          } elsif ($r eq 'HASH') {
435           &cast((ref() ? $_ : \$_), $wiz, $depth + 1) for values %$var;
436          }
437          return $depth;
438         },
439         free => sub {
440          my ($var, $depth) = @_;
441          my $r = ref $var;
442          print "free $r at depth $depth\n";
443          ();
444         };
445
446         {
447          my %h = (
448           a => [ 1, 2 ],
449           b => { c => 3 }
450          );
451          cast %h, $wiz;
452         }
453
454     When %h goes out of scope, this will print something among the lines of
455     :
456
457         free HASH at depth 0
458         free HASH at depth 1
459         free SCALAR at depth 2
460         free ARRAY at depth 1
461         free SCALAR at depth 3
462         free SCALAR at depth 3
463
464     Of course, this example does nothing with the values that are added
465     after the "cast".
466
467 PERL MAGIC HISTORY
468     The places where magic is invoked have changed a bit through perl
469     history. Here's a little list of the most recent ones.
470
471     *   5.6.x
472
473         *p14416* : 'copy' and 'dup' magic.
474
475     *   5.8.9
476
477         *p28160* : Integration of *p25854* (see below).
478
479         *p32542* : Integration of *p31473* (see below).
480
481     *   5.9.3
482
483         *p25854* : 'len' magic is no longer called when pushing an element
484         into a magic array.
485
486         *p26569* : 'local' magic.
487
488     *   5.9.5
489
490         *p31064* : Meaningful 'uvar' magic.
491
492         *p31473* : 'clear' magic wasn't invoked when undefining an array.
493         The bug is fixed as of this version.
494
495     *   5.10.0
496
497         Since "PERL_MAGIC_uvar" is uppercased, "hv_magic_check()" triggers
498         'copy' magic on hash stores for (non-tied) hashes that also have
499         'uvar' magic.
500
501     *   5.11.x
502
503         *p32969* : 'len' magic is no longer invoked when calling "length"
504         with a magical scalar.
505
506         *p34908* : 'len' magic is no longer called when pushing / unshifting
507         an element into a magical array in void context. The "push" part was
508         already covered by *p25854*.
509
510         *g9cdcb38b* : 'len' magic is called again when pushing into a
511         magical array in non-void context.
512
513 EXPORT
514     The functions "wizard", "gensig", "getsig", "cast", "getdata" and
515     "dispell" are only exported on request. All of them are exported by the
516     tags ':funcs' and ':all'.
517
518     All the constants are also only exported on request, either individually
519     or by the tags ':consts' and ':all'.
520
521 CAVEATS
522     If you store a magic object in the private data slot, the magic won't be
523     accessible by "getdata" since it's not copied by assignment. The only
524     way to address this would be to return a reference.
525
526     If you define a wizard with a "free" callback and cast it on itself,
527     this destructor won't be called because the wizard will be destroyed
528     first.
529
530 DEPENDENCIES
531     perl 5.8.
532
533     Carp (standard since perl 5), XSLoader (standard since perl 5.006).
534
535     Copy tests need Tie::Array (standard since perl 5.005) and Tie::Hash
536     (since 5.002).
537
538     Some uvar tests need Hash::Util::FieldHash (standard since perl
539     5.009004).
540
541     Glob tests need Symbol (standard since perl 5.002).
542
543     Threads tests need threads and threads::shared.
544
545 SEE ALSO
546     perlguts and perlapi for internal information about magic.
547
548     perltie and overload for other ways of enhancing objects.
549
550 AUTHOR
551     Vincent Pit, "<perl at profvince.com>", <http://www.profvince.com>.
552
553     You can contact me by mail or on "irc.perl.org" (vincent).
554
555 BUGS
556     Please report any bugs or feature requests to "bug-variable-magic at
557     rt.cpan.org", or through the web interface at
558     <http://rt.cpan.org/NoAuth/ReportBug.html?Queue=Variable-Magic>. I will
559     be notified, and then you'll automatically be notified of progress on
560     your bug as I make changes.
561
562 SUPPORT
563     You can find documentation for this module with the perldoc command.
564
565         perldoc Variable::Magic
566
567     Tests code coverage report is available at
568     <http://www.profvince.com/perl/cover/Variable-Magic>.
569
570 COPYRIGHT & LICENSE
571     Copyright 2007-2009 Vincent Pit, all rights reserved.
572
573     This program is free software; you can redistribute it and/or modify it
574     under the same terms as Perl itself.
575