]> git.vpit.fr Git - perl/modules/Variable-Magic.git/blob - README
Simplify vmg_call_sv() so that ERRSV is no longer used as a lvalue
[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.55
6
7 SYNOPSIS
8         use Variable::Magic qw<wizard cast VMG_OP_INFO_NAME>;
9
10         { # A variable tracer
11          my $wiz = wizard(
12           set  => sub { print "now set to ${$_[0]}!\n" },
13           free => sub { print "destroyed!\n" },
14          );
15
16          my $a = 1;
17          cast $a, $wiz;
18          $a = 2;        # "now set to 2!"
19         }               # "destroyed!"
20
21         { # A hash with a default value
22          my $wiz = wizard(
23           data     => sub { $_[1] },
24           fetch    => sub { $_[2] = $_[1] unless exists $_[0]->{$_[2]}; () },
25           store    => sub { print "key $_[2] stored in $_[-1]\n" },
26           copy_key => 1,
27           op_info  => VMG_OP_INFO_NAME,
28          );
29
30          my %h = (_default => 0, apple => 2);
31          cast %h, $wiz, '_default';
32          print $h{banana}, "\n"; # "0" (there is no 'banana' key in %h)
33          $h{pear} = 1;           # "key pear stored in helem"
34         }
35
36 DESCRIPTION
37     Magic is Perl's way of enhancing variables. This mechanism lets the user
38     add extra data to any variable and hook syntactical operations (such as
39     access, assignment or destruction) that can be applied to it. With this
40     module, you can add your own magic to any variable without having to
41     write a single line of XS.
42
43     You'll realize that these magic variables look a lot like tied
44     variables. It is not surprising, as tied variables are implemented as a
45     special kind of magic, just like any 'irregular' Perl variable : scalars
46     like $!, $( or $^W, the %ENV and %SIG hashes, the @ISA array, "vec()"
47     and "substr()" lvalues, threads::shared variables... They all share the
48     same underlying C API, and this module gives you direct access to it.
49
50     Still, the magic made available by this module differs from tieing and
51     overloading in several ways :
52
53     *   Magic is not copied on assignment.
54
55         You attach it to variables, not values (as for blessed references).
56
57     *   Magic does not replace the original semantics.
58
59         Magic callbacks usually get triggered before the original action
60         takes place, and cannot prevent it from happening. This also makes
61         catching individual events easier than with "tie", where you have to
62         provide fallbacks methods for all actions by usually inheriting from
63         the correct "Tie::Std*" class and overriding individual methods in
64         your own class.
65
66     *   Magic is multivalued.
67
68         You can safely apply different kinds of magics to the same variable,
69         and each of them will be invoked successively.
70
71     *   Magic is type-agnostic.
72
73         The same magic can be applied on scalars, arrays, hashes, subs or
74         globs. But the same hook (see below for a list) may trigger
75         differently depending on the type of the variable.
76
77     *   Magic is invisible at Perl level.
78
79         Magical and non-magical variables cannot be distinguished with
80         "ref", "tied" or another trick.
81
82     *   Magic is notably faster.
83
84         Mainly because perl's way of handling magic is lighter by nature,
85         and because there is no need for any method resolution. Also, since
86         you don't have to reimplement all the variable semantics, you only
87         pay for what you actually use.
88
89     The operations that can be overloaded are :
90
91     *   *get*
92
93         This magic is invoked when the variable is evaluated. It is never
94         called for arrays and hashes.
95
96     *   *set*
97
98         This magic is called each time the value of the variable changes. It
99         is called for array subscripts and slices, but never for hashes.
100
101     *   *len*
102
103         This magic only applies to arrays (though it used to also apply to
104         scalars), and is triggered when the 'size' or the 'length' of the
105         variable has to be known by Perl. This is typically the magic
106         involved when an array is evaluated in scalar context, but also on
107         array assignment and loops ("for", "map" or "grep"). The length is
108         returned from the callback as an integer.
109
110         Starting from perl 5.12, this magic is no longer called by the
111         "length" keyword, and starting from perl 5.17.4 it is also no longer
112         called for scalars in any situation, making this magic only
113         meaningful on arrays. You can use the constants
114         "VMG_COMPAT_SCALAR_LENGTH_NOLEN" and "VMG_COMPAT_SCALAR_NOLEN" to
115         see if this magic is available for scalars or not.
116
117     *   *clear*
118
119         This magic is invoked when the variable is reset, such as when an
120         array is emptied. Please note that this is different from undefining
121         the variable, even though the magic is called when the clearing is a
122         result of the undefine (e.g. for an array, but actually a bug
123         prevent it to work before perl 5.9.5 - see the history).
124
125     *   *free*
126
127         This magic is called when a variable is destroyed as the result of
128         going out of scope (but not when it is undefined). It behaves
129         roughly like Perl object destructors (i.e. "DESTROY" methods),
130         except that exceptions thrown from inside a *free* callback will
131         always be propagated to the surrounding code.
132
133     *   *copy*
134
135         When applied to tied arrays and hashes, this magic fires when you
136         try to access or change their elements.
137
138         Starting from perl 5.17.0, it can also be applied to closure
139         prototypes, in which case the magic will be called when the
140         prototype is cloned. The "VMG_COMPAT_CODE_COPY_CLONE" constant is
141         true when your perl support this feature.
142
143     *   *dup*
144
145         This magic is invoked when the variable is cloned across threads. It
146         is currently not available.
147
148     *   *local*
149
150         When this magic is set on a variable, all subsequent localizations
151         of the variable will trigger the callback. It is available on your
152         perl if and only if "MGf_LOCAL" is true.
153
154     The following actions only apply to hashes and are available if and only
155     if "VMG_UVAR" is true. They are referred to as *uvar* magics.
156
157     *   *fetch*
158
159         This magic is invoked each time an element is fetched from the hash.
160
161     *   *store*
162
163         This one is called when an element is stored into the hash.
164
165     *   *exists*
166
167         This magic fires when a key is tested for existence in the hash.
168
169     *   *delete*
170
171         This magic is triggered when a key is deleted in the hash,
172         regardless of whether the key actually exists in it.
173
174     You can refer to the tests to have more insight of where the different
175     magics are invoked.
176
177 FUNCTIONS
178   "wizard"
179         wizard(
180          data     => sub { ... },
181          get      => sub { my ($ref, $data [, $op]) = @_; ... },
182          set      => sub { my ($ref, $data [, $op]) = @_; ... },
183          len      => sub {
184           my ($ref, $data, $len [, $op]) = @_; ... ; return $newlen
185          },
186          clear    => sub { my ($ref, $data [, $op]) = @_; ... },
187          free     => sub { my ($ref, $data [, $op]) = @_, ... },
188          copy     => sub { my ($ref, $data, $key, $elt [, $op]) = @_; ... },
189          local    => sub { my ($ref, $data [, $op]) = @_; ... },
190          fetch    => sub { my ($ref, $data, $key [, $op]) = @_; ... },
191          store    => sub { my ($ref, $data, $key [, $op]) = @_; ... },
192          exists   => sub { my ($ref, $data, $key [, $op]) = @_; ... },
193          delete   => sub { my ($ref, $data, $key [, $op]) = @_; ... },
194          copy_key => $bool,
195          op_info  => [ 0 | VMG_OP_INFO_NAME | VMG_OP_INFO_OBJECT ],
196         )
197
198     This function creates a 'wizard', an opaque object that holds the magic
199     information. It takes a list of keys / values as argument, whose keys
200     can be :
201
202     *   "data"
203
204         A code (or string) reference to a private data constructor. It is
205         called in scalar context each time the magic is cast onto a
206         variable, with $_[0] being a reference to this variable and @_[1 ..
207         @_-1] being all extra arguments that were passed to "cast". The
208         scalar returned from this call is then attached to the variable and
209         can be retrieved later with "getdata".
210
211     *   "get", "set", "len", "clear", "free", "copy", "local", "fetch",
212         "store", "exists" and "delete"
213
214         Code (or string) references to the respective magic callbacks. You
215         don't have to specify all of them : the magic corresponding to
216         undefined entries will simply not be hooked.
217
218         When those callbacks are executed, $_[0] is a reference to the magic
219         variable and $_[1] is the associated private data (or "undef" when
220         no private data constructor is supplied with the wizard). Other
221         arguments depend on which kind of magic is involved :
222
223         *       *len*
224
225                 $_[2] contains the natural, non-magical length of the
226                 variable (which can only be a scalar or an array as *len*
227                 magic is only relevant for these types). The callback is
228                 expected to return the new scalar or array length to use, or
229                 "undef" to default to the normal length.
230
231         *       *copy*
232
233                 When the variable for which the magic is invoked is an array
234                 or an hash, $_[2] is a either an alias or a copy of the
235                 current key, and $_[3] is an alias to the current element
236                 (i.e. the value). Since $_[2] might be a copy, it is useless
237                 to try to change it or cast magic on it.
238
239                 Starting from perl 5.17.0, this magic can also be called for
240                 code references. In this case, $_[2] is always "undef" and
241                 $_[3] is a reference to the cloned anonymous subroutine.
242
243         *       *fetch*, *store*, *exists* and *delete*
244
245                 $_[2] is an alias to the current key. Note that $_[2] may
246                 rightfully be readonly if the key comes from a bareword, and
247                 as such it is unsafe to assign to it. You can ask for a copy
248                 instead by passing "copy_key => 1" to "wizard" which, at the
249                 price of a small performance hit, allows you to safely
250                 assign to $_[2] in order to e.g. redirect the action to
251                 another key.
252
253         Finally, if "op_info => $num" is also passed to "wizard", then one
254         extra element is appended to @_. Its nature depends on the value of
255         $num :
256
257         *       "VMG_OP_INFO_NAME"
258
259                 $_[-1] is the current op name.
260
261         *       "VMG_OP_INFO_OBJECT"
262
263                 $_[-1] is the "B::OP" object for the current op.
264
265         Both result in a small performance hit, but just getting the name is
266         lighter than getting the op object.
267
268         These callbacks are executed in scalar context and are expected to
269         return an integer, which is then passed straight to the perl magic
270         API. However, only the return value of the *len* magic callback
271         currently holds a meaning.
272
273     Each callback can be specified as :
274
275     *   a code reference, which will be called as a subroutine.
276
277     *   a string reference, where the string denotes which subroutine is to
278         be called when magic is triggered. If the subroutine name is not
279         fully qualified, then the current package at the time the magic is
280         invoked will be used instead.
281
282     *   a reference to "undef", in which case a no-op magic callback is
283         installed instead of the default one. This may especially be helpful
284         for *local* magic, where an empty callback prevents magic from being
285         copied during localization.
286
287     Note that *free* magic is never called during global destruction, as
288     there is no way to ensure that the wizard object and the callback were
289     not destroyed before the variable.
290
291     Here is a simple usage example :
292
293         # A simple scalar tracer
294         my $wiz = wizard(
295          get  => sub { print STDERR "got ${$_[0]}\n" },
296          set  => sub { print STDERR "set to ${$_[0]}\n" },
297          free => sub { print STDERR "${$_[0]} was deleted\n" },
298         );
299
300   "cast"
301         cast [$@%&*]var, $wiz, @args
302
303     This function associates $wiz magic to the supplied variable, without
304     overwriting any other kind of magic. It returns true on success or when
305     $wiz magic is already attached, and croaks on error. When $wiz provides
306     a data constructor, it is called just before magic is cast onto the
307     variable, and it receives a reference to the target variable in $_[0]
308     and the content of @args in @_[1 .. @args]. Otherwise, @args is ignored.
309
310         # Casts $wiz onto $x, passing (\$x, '1') to the data constructor.
311         my $x;
312         cast $x, $wiz, 1;
313
314     The "var" argument can be an array or hash value. Magic for these
315     scalars behaves like for any other, except that it is dispelled when the
316     entry is deleted from the container. For example, if you want to call
317     "POSIX::tzset" each time the 'TZ' environment variable is changed in
318     %ENV, you can use :
319
320         use POSIX;
321         cast $ENV{TZ}, wizard set => sub { POSIX::tzset(); () };
322
323     If you want to handle the possible deletion of the 'TZ' entry, you must
324     also specify *store* magic.
325
326   "getdata"
327         getdata [$@%&*]var, $wiz
328
329     This accessor fetches the private data associated with the magic $wiz in
330     the variable. It croaks when $wiz does not represent a valid magic
331     object, and returns an empty list if no such magic is attached to the
332     variable or when the wizard has no data constructor.
333
334         # Get the data attached to $wiz in $x, or undef if $wiz
335         # did not attach any.
336         my $data = getdata $x, $wiz;
337
338   "dispell"
339         dispell [$@%&*]variable, $wiz
340
341     The exact opposite of "cast" : it dissociates $wiz magic from the
342     variable. This function returns true on success, 0 when no magic
343     represented by $wiz could be found in the variable, and croaks if the
344     supplied wizard is invalid.
345
346         # Dispell now.
347         die 'no such magic in $x' unless dispell $x, $wiz;
348
349 CONSTANTS
350   "MGf_COPY"
351     Evaluates to true if and only if the *copy* magic is available. This is
352     the case for perl 5.7.3 and greater, which is ensured by the
353     requirements of this module.
354
355   "MGf_DUP"
356     Evaluates to true if and only if the *dup* magic is available. This is
357     the case for perl 5.7.3 and greater, which is ensured by the
358     requirements of this module.
359
360   "MGf_LOCAL"
361     Evaluates to true if and only if the *local* magic is available. This is
362     the case for perl 5.9.3 and greater.
363
364   "VMG_UVAR"
365     When this constant is true, you can use the *fetch*, *store*, *exists*
366     and *delete* magics on hashes. Initial "VMG_UVAR" capability was
367     introduced in perl 5.9.5, with a fully functional implementation shipped
368     with perl 5.10.0.
369
370   "VMG_COMPAT_SCALAR_LENGTH_NOLEN"
371     True for perls that don't call *len* magic when taking the "length" of a
372     magical scalar.
373
374   "VMG_COMPAT_SCALAR_NOLEN"
375     True for perls that don't call *len* magic on scalars. Implies
376     "VMG_COMPAT_SCALAR_LENGTH_NOLEN".
377
378   "VMG_COMPAT_ARRAY_PUSH_NOLEN"
379     True for perls that don't call *len* magic when you push an element in a
380     magical array. Starting from perl 5.11.0, this only refers to pushes in
381     non-void context and hence is false.
382
383   "VMG_COMPAT_ARRAY_PUSH_NOLEN_VOID"
384     True for perls that don't call *len* magic when you push in void context
385     an element in a magical array.
386
387   "VMG_COMPAT_ARRAY_UNSHIFT_NOLEN_VOID"
388     True for perls that don't call *len* magic when you unshift in void
389     context an element in a magical array.
390
391   "VMG_COMPAT_ARRAY_UNDEF_CLEAR"
392     True for perls that call *clear* magic when undefining magical arrays.
393
394   "VMG_COMPAT_HASH_DELETE_NOUVAR_VOID"
395     True for perls that don't call *delete* magic when you delete an element
396     from a hash in void context.
397
398   "VMG_COMPAT_CODE_COPY_CLONE"
399     True for perls that call *copy* magic when a magical closure prototype
400     is cloned.
401
402   "VMG_COMPAT_GLOB_GET"
403     True for perls that call *get* magic for operations on globs.
404
405   "VMG_PERL_PATCHLEVEL"
406     The perl patchlevel this module was built with, or 0 for non-debugging
407     perls.
408
409   "VMG_THREADSAFE"
410     True if and only if this module could have been built with thread-safety
411     features enabled.
412
413   "VMG_FORKSAFE"
414     True if and only if this module could have been built with fork-safety
415     features enabled. This is always true except on Windows where it is
416     false for perl 5.10.0 and below.
417
418   "VMG_OP_INFO_NAME"
419     Value to pass with "op_info" to get the current op name in the magic
420     callbacks.
421
422   "VMG_OP_INFO_OBJECT"
423     Value to pass with "op_info" to get a "B::OP" object representing the
424     current op in the magic callbacks.
425
426 COOKBOOK
427   Associate an object to any perl variable
428     This technique can be useful for passing user data through limited APIs.
429     It is similar to using inside-out objects, but without the drawback of
430     having to implement a complex destructor.
431
432         {
433          package Magical::UserData;
434
435          use Variable::Magic qw<wizard cast getdata>;
436
437          my $wiz = wizard data => sub { \$_[1] };
438
439          sub ud (\[$@%*&]) : lvalue {
440           my ($var) = @_;
441           my $data = &getdata($var, $wiz);
442           unless (defined $data) {
443            $data = \(my $slot);
444            &cast($var, $wiz, $slot)
445                      or die "Couldn't cast UserData magic onto the variable";
446           }
447           $$data;
448          }
449         }
450
451         {
452          BEGIN { *ud = \&Magical::UserData::ud }
453
454          my $cb;
455          $cb = sub { print 'Hello, ', ud(&$cb), "!\n" };
456
457          ud(&$cb) = 'world';
458          $cb->(); # Hello, world!
459         }
460
461   Recursively cast magic on datastructures
462     "cast" can be called from any magical callback, and in particular from
463     "data". This allows you to recursively cast magic on datastructures :
464
465         my $wiz;
466         $wiz = wizard data => sub {
467          my ($var, $depth) = @_;
468          $depth ||= 0;
469          my $r = ref $var;
470          if ($r eq 'ARRAY') {
471           &cast((ref() ? $_ : \$_), $wiz, $depth + 1) for @$var;
472          } elsif ($r eq 'HASH') {
473           &cast((ref() ? $_ : \$_), $wiz, $depth + 1) for values %$var;
474          }
475          return $depth;
476         },
477         free => sub {
478          my ($var, $depth) = @_;
479          my $r = ref $var;
480          print "free $r at depth $depth\n";
481          ();
482         };
483
484         {
485          my %h = (
486           a => [ 1, 2 ],
487           b => { c => 3 }
488          );
489          cast %h, $wiz;
490         }
491
492     When %h goes out of scope, this prints something among the lines of :
493
494         free HASH at depth 0
495         free HASH at depth 1
496         free SCALAR at depth 2
497         free ARRAY at depth 1
498         free SCALAR at depth 3
499         free SCALAR at depth 3
500
501     Of course, this example does nothing with the values that are added
502     after the "cast".
503
504 PERL MAGIC HISTORY
505     The places where magic is invoked have changed a bit through perl
506     history. Here is a little list of the most recent ones.
507
508     *   5.6.x
509
510         *p14416* : *copy* and *dup* magic.
511
512     *   5.8.9
513
514         *p28160* : Integration of *p25854* (see below).
515
516         *p32542* : Integration of *p31473* (see below).
517
518     *   5.9.3
519
520         *p25854* : *len* magic is no longer called when pushing an element
521         into a magic array.
522
523         *p26569* : *local* magic.
524
525     *   5.9.5
526
527         *p31064* : Meaningful *uvar* magic.
528
529         *p31473* : *clear* magic was not invoked when undefining an array.
530         The bug is fixed as of this version.
531
532     *   5.10.0
533
534         Since "PERL_MAGIC_uvar" is uppercased, "hv_magic_check()" triggers
535         *copy* magic on hash stores for (non-tied) hashes that also have
536         *uvar* magic.
537
538     *   5.11.x
539
540         *p32969* : *len* magic is no longer invoked when calling "length"
541         with a magical scalar.
542
543         *p34908* : *len* magic is no longer called when pushing / unshifting
544         an element into a magical array in void context. The "push" part was
545         already covered by *p25854*.
546
547         *g9cdcb38b* : *len* magic is called again when pushing into a
548         magical array in non-void context.
549
550 EXPORT
551     The functions "wizard", "cast", "getdata" and "dispell" are only
552     exported on request. All of them are exported by the tags ':funcs' and
553     ':all'.
554
555     All the constants are also only exported on request, either individually
556     or by the tags ':consts' and ':all'.
557
558 CAVEATS
559     In order to hook hash operations with magic, you need at least perl
560     5.10.0 (see "VMG_UVAR").
561
562     If you want to store a magic object in the private data slot, you will
563     not be able to recover the magic with "getdata", since magic is not
564     copied by assignment. You can work around this gotcha by storing a
565     reference to the magic object instead.
566
567     If you define a wizard with *free* magic and cast it on itself, it
568     results in a memory cycle, so this destructor will not be called when
569     the wizard is freed.
570
571 DEPENDENCIES
572     perl 5.8.
573
574     A C compiler. This module may happen to build with a C++ compiler as
575     well, but don't rely on it, as no guarantee is made in this regard.
576
577     Carp (core since perl 5), XSLoader (since 5.6.0).
578
579 SEE ALSO
580     perlguts and perlapi for internal information about magic.
581
582     perltie and overload for other ways of enhancing objects.
583
584 AUTHOR
585     Vincent Pit, "<perl at profvince.com>", <http://www.profvince.com>.
586
587     You can contact me by mail or on "irc.perl.org" (vincent).
588
589 BUGS
590     Please report any bugs or feature requests to "bug-variable-magic at
591     rt.cpan.org", or through the web interface at
592     <http://rt.cpan.org/NoAuth/ReportBug.html?Queue=Variable-Magic>. I will
593     be notified, and then you'll automatically be notified of progress on
594     your bug as I make changes.
595
596 SUPPORT
597     You can find documentation for this module with the perldoc command.
598
599         perldoc Variable::Magic
600
601     Tests code coverage report is available at
602     <http://www.profvince.com/perl/cover/Variable-Magic>.
603
604 COPYRIGHT & LICENSE
605     Copyright 2007,2008,2009,2010,2011,2012,2013,2014 Vincent Pit, all
606     rights reserved.
607
608     This program is free software; you can redistribute it and/or modify it
609     under the same terms as Perl itself.
610