1Variable::Magic(3)    User Contributed Perl Documentation   Variable::Magic(3)
2
3
4

NAME

6       Variable::Magic - Associate user-defined magic to variables from Perl.
7

VERSION

9       Version 0.43
10

SYNOPSIS

12           use Variable::Magic qw/wizard cast VMG_OP_INFO_NAME/;
13
14           { # A variable tracer
15            my $wiz = wizard set  => sub { print "now set to ${$_[0]}!\n" },
16                             free => sub { print "destroyed!\n" };
17
18            my $a = 1;
19            cast $a, $wiz;
20            $a = 2;        # "now set to 2!"
21           }               # "destroyed!"
22
23           { # A hash with a default value
24            my $wiz = wizard data     => sub { $_[1] },
25                             fetch    => sub { $_[2] = $_[1] unless exists $_[0]->{$_[2]}; () },
26                             store    => sub { print "key $_[2] stored in $_[-1]\n" },
27                             copy_key => 1,
28                             op_info  => VMG_OP_INFO_NAME;
29
30            my %h = (_default => 0, apple => 2);
31            cast %h, $wiz, '_default';
32            print $h{banana}, "\n"; # "0", because the 'banana' key doesn't exist in %h
33            $h{pear} = 1;           # "key pear stored in helem"
34           }
35

DESCRIPTION

37       Magic is Perl's way of enhancing variables.  This mechanism lets the
38       user add extra data to any variable and hook syntactical operations
39       (such as access, assignment or destruction) that can be applied to it.
40       With this module, you can add your own magic to any variable without
41       having to write a single line of XS.
42
43       You'll realize that these magic variables look a lot like tied
44       variables.  It's not surprising, as tied variables are implemented as a
45       special kind of magic, just like any 'irregular' Perl variable :
46       scalars like $!, $( or $^W, the %ENV and %SIG hashes, the @ISA array,
47       "vec()" and "substr()" lvalues, threads::shared variables...  They all
48       share the same underlying C API, and this module gives you direct
49       access to it.
50
51       Still, the magic made available by this module differs from tieing and
52       overloading in several ways :
53
54       ·   It isn't copied on assignment.
55
56           You attach it to variables, not values (as for blessed references).
57
58       ·   It doesn't replace the original semantics.
59
60           Magic callbacks usually get triggered before the original action
61           takes place, and can't prevent it from happening.  This also makes
62           catching individual events easier than with "tie", where you have
63           to provide fallbacks methods for all actions by usually inheriting
64           from the correct "Tie::Std*" class and overriding individual
65           methods in your own class.
66
67       ·   It's type-agnostic.
68
69           The same magic can be applied on scalars, arrays, hashes, subs or
70           globs.  But the same hook (see below for a list) may trigger
71           differently depending on the the type of the variable.
72
73       ·   It's mostly invisible at the Perl level.
74
75           Magical and non-magical variables cannot be distinguished with
76           "ref", "tied" or another trick.
77
78       ·   It's notably faster.
79
80           Mainly because perl's way of handling magic is lighter by nature,
81           and because there's no need for any method resolution.  Also, since
82           you don't have to reimplement all the variable semantics, you only
83           pay for what you actually use.
84
85       The operations that can be overloaded are :
86
87       ·   "get"
88
89           This magic is invoked when the variable is evaluated.  It is never
90           called for arrays and hashes.
91
92       ·   "set"
93
94           This one is triggered each time the value of the variable changes.
95           It is called for array subscripts and slices, but never for hashes.
96
97       ·   "len"
98
99           This magic is a little special : it is called when the 'size' or
100           the 'length' of the variable has to be known by Perl.  Typically,
101           it's the magic involved when an array is evaluated in scalar
102           context, but also on array assignment and loops ("for", "map" or
103           "grep").  The callback has then to return the length as an integer.
104
105       ·   "clear"
106
107           This magic is invoked when the variable is reset, such as when an
108           array is emptied.  Please note that this is different from
109           undefining the variable, even though the magic is called when the
110           clearing is a result of the undefine (e.g. for an array, but
111           actually a bug prevent it to work before perl 5.9.5 - see the
112           history).
113
114       ·   "free"
115
116           This one can be considered as an object destructor.  It happens
117           when the variable goes out of scope, but not when it is undefined.
118
119       ·   "copy"
120
121           This magic only applies to tied arrays and hashes.  It fires when
122           you try to access or change their elements.  It is available on
123           your perl iff "MGf_COPY" is true.
124
125       ·   "dup"
126
127           Invoked when the variable is cloned across threads.  Currently not
128           available.
129
130       ·   "local"
131
132           When this magic is set on a variable, all subsequent localizations
133           of the variable will trigger the callback.  It is available on your
134           perl iff "MGf_LOCAL" is true.
135
136       The following actions only apply to hashes and are available iff
137       "VMG_UVAR" is true.  They are referred to as "uvar" magics.
138
139       ·   "fetch"
140
141           This magic happens each time an element is fetched from the hash.
142
143       ·   "store"
144
145           This one is called when an element is stored into the hash.
146
147       ·   "exists"
148
149           This magic fires when a key is tested for existence in the hash.
150
151       ·   "delete"
152
153           This last one triggers when a key is deleted in the hash,
154           regardless of whether the key actually exists in it.
155
156       You can refer to the tests to have more insight of where the different
157       magics are invoked.
158
159       To prevent any clash between different magics defined with this module,
160       an unique numerical signature is attached to each kind of magic (i.e.
161       each set of callbacks for magic operations).  At the C level, magic
162       tokens owned by magic created by this module have their
163       "mg->mg_private" field set to 0x3891 or 0x3892, so please don't use
164       these magic (sic) numbers in other extensions.
165

FUNCTIONS

167   "wizard"
168           wizard data     => sub { ... },
169                  get      => sub { my ($ref, $data [, $op]) = @_; ... },
170                  set      => sub { my ($ref, $data [, $op]) = @_; ... },
171                  len      => sub { my ($ref, $data, $len [, $op]) = @_; ... ; return $newlen; },
172                  clear    => sub { my ($ref, $data [, $op]) = @_; ... },
173                  free     => sub { my ($ref, $data [, $op]) = @_, ... },
174                  copy     => sub { my ($ref, $data, $key, $elt [, $op]) = @_; ... },
175                  local    => sub { my ($ref, $data [, $op]) = @_; ... },
176                  fetch    => sub { my ($ref, $data, $key [, $op]) = @_; ... },
177                  store    => sub { my ($ref, $data, $key [, $op]) = @_; ... },
178                  exists   => sub { my ($ref, $data, $key [, $op]) = @_; ... },
179                  delete   => sub { my ($ref, $data, $key [, $op]) = @_; ... },
180                  copy_key => $bool,
181                  op_info  => [ 0 | VMG_OP_INFO_NAME | VMG_OP_INFO_OBJECT ]
182
183       This function creates a 'wizard', an opaque type that holds the magic
184       information.  It takes a list of keys / values as argument, whose keys
185       can be :
186
187       ·   "data"
188
189           A code (or string) reference to a private data constructor.  It is
190           called each time this magic is cast on a variable, and the scalar
191           returned is used as private data storage for it.  $_[0] is a
192           reference to the magic object and @_[1 .. @_-1] are all extra
193           arguments that were passed to "cast".
194
195       ·   "get", "set", "len", "clear", "free", "copy", "local", "fetch",
196           "store", "exists" and "delete"
197
198           Code (or string) references to the corresponding magic callbacks.
199           You don't have to specify all of them : the magic associated with
200           undefined entries simply won't be hooked.  In those callbacks,
201           $_[0] is always a reference to the magic object and $_[1] is always
202           the private data (or "undef" when no private data constructor was
203           supplied).
204
205           Moreover, when you pass "op_info => $num" to "wizard", the last
206           element of @_ will be the current op name if "$num ==
207           VMG_OP_INFO_NAME" and a "B::OP" object representing the current op
208           if "$num == VMG_OP_INFO_OBJECT".  Both have a performance hit, but
209           just getting the name is lighter than getting the op object.
210
211           Other arguments are specific to the magic hooked :
212
213           ·       "len"
214
215                   When the variable is an array or a scalar, $_[2] contains
216                   the non-magical length.  The callback can return the new
217                   scalar or array length to use, or "undef" to default to the
218                   normal length.
219
220           ·       "copy"
221
222                   $_[2] is a either a copy or an alias of the current key,
223                   which means that it is useless to try to change or cast
224                   magic on it.  $_[3] is an alias to the current element
225                   (i.e. the value).
226
227           ·       "fetch", "store", "exists" and "delete"
228
229                   $_[2] is an alias to the current key.  Nothing prevents you
230                   from changing it, but be aware that there lurk dangerous
231                   side effects.  For example, it may rightfully be readonly
232                   if the key was a bareword.  You can get a copy instead by
233                   passing "copy_key => 1" to "wizard", which allows you to
234                   safely assign to $_[2] in order to e.g. redirect the action
235                   to another key.  This however has a little performance
236                   drawback because of the copy.
237
238           All the callbacks are expected to return an integer, which is
239           passed straight to the perl magic API.  However, only the return
240           value of the "len" callback currently holds a meaning.
241
242       Each callback can be specified as a code or a string reference, in
243       which case the function denoted by the string will be used as the
244       callback.
245
246       Note that "free" callbacks are never called during global destruction,
247       as there's no way to ensure that the wizard and the "free" callback
248       weren't destroyed before the variable.
249
250       Here's a simple usage example :
251
252           # A simple scalar tracer
253           my $wiz = wizard get  => sub { print STDERR "got ${$_[0]}\n" },
254                            set  => sub { print STDERR "set to ${$_[0]}\n" },
255                            free => sub { print STDERR "${$_[0]} was deleted\n" }
256
257   "cast"
258           cast [$@%&*]var, $wiz, ...
259
260       This function associates $wiz magic to the variable supplied, without
261       overwriting any other kind of magic.  It returns true on success or
262       when $wiz magic is already present, and croaks on error.  All extra
263       arguments specified after $wiz are passed to the private data
264       constructor in @_[1 .. @_-1].  If the variable isn't a hash, any "uvar"
265       callback of the wizard is safely ignored.
266
267           # Casts $wiz onto $x, and pass '1' to the data constructor.
268           my $x;
269           cast $x, $wiz, 1;
270
271       The "var" argument can be an array or hash value.  Magic for those
272       behaves like for any other scalar, except that it is dispelled when the
273       entry is deleted from the container.  For example, if you want to call
274       "POSIX::tzset" each time the 'TZ' environment variable is changed in
275       %ENV, you can use :
276
277           use POSIX;
278           cast $ENV{TZ}, wizard set => sub { POSIX::tzset(); () };
279
280       If you want to overcome the possible deletion of the 'TZ' entry, you
281       have no choice but to rely on "store" uvar magic.
282
283   "getdata"
284           getdata [$@%&*]var, $wiz
285
286       This accessor fetches the private data associated with the magic $wiz
287       in the variable.  It croaks when $wiz do not represent a valid magic
288       object, and returns an empty list if no such magic is attached to the
289       variable or when the wizard has no data constructor.
290
291           # Get the attached data, or undef if the wizard does not attach any.
292           my $data = getdata $x, $wiz;
293
294   "dispell"
295           dispell [$@%&*]variable, $wiz
296
297       The exact opposite of "cast" : it dissociates $wiz magic from the
298       variable.  This function returns true on success, 0 when no magic
299       represented by $wiz could be found in the variable, and croaks if the
300       supplied wizard is invalid.
301
302           # Dispell now.
303           die 'no such magic in $x' unless dispell $x, $wiz;
304

CONSTANTS

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
321       a magical array.  Starting from perl 5.11.0, this only refers to pushes
322       in non-void context and hence is false.
323
324   "VMG_COMPAT_ARRAY_PUSH_NOLEN_VOID"
325       True for perls that don't call 'len' magic when you push in void
326       context an element in a magical array.
327
328   "VMG_COMPAT_ARRAY_UNSHIFT_NOLEN_VOID"
329       True for perls that don't call 'len' magic when you unshift in void
330       context an element in a magical array.
331
332   "VMG_COMPAT_ARRAY_UNDEF_CLEAR"
333       True for perls that call 'clear' magic when undefining magical arrays.
334
335   "VMG_COMPAT_SCALAR_LENGTH_NOLEN"
336       True for perls that don't call 'len' magic when taking the "length" of
337       a magical scalar.
338
339   "VMG_COMPAT_GLOB_GET"
340       True for perls that call 'get' magic for operations on globs.
341
342   "VMG_PERL_PATCHLEVEL"
343       The perl patchlevel this module was built with, or 0 for non-debugging
344       perls.
345
346   "VMG_THREADSAFE"
347       True iff this module could have been built with thread-safety features
348       enabled.
349
350   "VMG_FORKSAFE"
351       True iff this module could have been built with fork-safety features
352       enabled.  This will always be true except on Windows where it's false
353       for perl 5.10.0 and below .
354
355   "VMG_OP_INFO_NAME"
356       Value to pass with "op_info" to get the current op name in the magic
357       callbacks.
358
359   "VMG_OP_INFO_OBJECT"
360       Value to pass with "op_info" to get a "B::OP" object representing the
361       current op in the magic callbacks.
362

COOKBOOK

364   Associate an object to any perl variable
365       This technique can be useful for passing user data through limited
366       APIs.  It is similar to using inside-out objects, but without the
367       drawback of having to implement a complex destructor.
368
369           {
370            package Magical::UserData;
371
372            use Variable::Magic qw/wizard cast getdata/;
373
374            my $wiz = wizard data => sub { \$_[1] };
375
376            sub ud (\[$@%*&]) : lvalue {
377             my ($var) = @_;
378             my $data = &getdata($var, $wiz);
379             unless (defined $data) {
380              $data = \(my $slot);
381              &cast($var, $wiz, $slot)
382                               or die "Couldn't cast UserData magic onto the variable";
383             }
384             $$data;
385            }
386           }
387
388           {
389            BEGIN { *ud = \&Magical::UserData::ud }
390
391            my $cb;
392            $cb = sub { print 'Hello, ', ud(&$cb), "!\n" };
393
394            ud(&$cb) = 'world';
395            $cb->(); # Hello, world!
396           }
397
398   Recursively cast magic on datastructures
399       "cast" can be called from any magical callback, and in particular from
400       "data".  This allows you to recursively cast magic on datastructures :
401
402           my $wiz;
403           $wiz = wizard data => sub {
404            my ($var, $depth) = @_;
405            $depth ||= 0;
406            my $r = ref $var;
407            if ($r eq 'ARRAY') {
408             &cast((ref() ? $_ : \$_), $wiz, $depth + 1) for @$var;
409            } elsif ($r eq 'HASH') {
410             &cast((ref() ? $_ : \$_), $wiz, $depth + 1) for values %$var;
411            }
412            return $depth;
413           },
414           free => sub {
415            my ($var, $depth) = @_;
416            my $r = ref $var;
417            print "free $r at depth $depth\n";
418            ();
419           };
420
421           {
422            my %h = (
423             a => [ 1, 2 ],
424             b => { c => 3 }
425            );
426            cast %h, $wiz;
427           }
428
429       When %h goes out of scope, this will print something among the lines of
430       :
431
432           free HASH at depth 0
433           free HASH at depth 1
434           free SCALAR at depth 2
435           free ARRAY at depth 1
436           free SCALAR at depth 3
437           free SCALAR at depth 3
438
439       Of course, this example does nothing with the values that are added
440       after the "cast".
441

PERL MAGIC HISTORY

443       The places where magic is invoked have changed a bit through perl
444       history.  Here's a little list of the most recent ones.
445
446       ·   5.6.x
447
448           p14416 : 'copy' and 'dup' magic.
449
450       ·   5.8.9
451
452           p28160 : Integration of p25854 (see below).
453
454           p32542 : Integration of p31473 (see below).
455
456       ·   5.9.3
457
458           p25854 : 'len' magic is no longer called when pushing an element
459           into a magic array.
460
461           p26569 : 'local' magic.
462
463       ·   5.9.5
464
465           p31064 : Meaningful 'uvar' magic.
466
467           p31473 : 'clear' magic wasn't invoked when undefining an array.
468           The bug is fixed as of this version.
469
470       ·   5.10.0
471
472           Since "PERL_MAGIC_uvar" is uppercased, "hv_magic_check()" triggers
473           'copy' magic on hash stores for (non-tied) hashes that also have
474           'uvar' magic.
475
476       ·   5.11.x
477
478           p32969 : 'len' magic is no longer invoked when calling "length"
479           with a magical scalar.
480
481           p34908 : 'len' magic is no longer called when pushing / unshifting
482           an element into a magical array in void context.  The "push" part
483           was already covered by p25854.
484
485           g9cdcb38b : 'len' magic is called again when pushing into a magical
486           array in non-void context.
487

EXPORT

489       The functions "wizard", "cast", "getdata" and "dispell" are only
490       exported on request.  All of them are exported by the tags ':funcs' and
491       ':all'.
492
493       All the constants are also only exported on request, either
494       individually or by the tags ':consts' and ':all'.
495

CAVEATS

497       If you store a magic object in the private data slot, the magic won't
498       be accessible by "getdata" since it's not copied by assignment.  The
499       only way to address this would be to return a reference.
500
501       If you define a wizard with a "free" callback and cast it on itself,
502       this destructor won't be called because the wizard will be destroyed
503       first.
504

DEPENDENCIES

506       perl 5.8.
507
508       Carp (standard since perl 5), XSLoader (standard since perl 5.006).
509
510       Copy tests need Tie::Array (standard since perl 5.005) and Tie::Hash
511       (since 5.002).
512
513       Some uvar tests need Hash::Util::FieldHash (standard since perl
514       5.009004).
515
516       Glob tests need Symbol (standard since perl 5.002).
517
518       Threads tests need threads and threads::shared.
519

SEE ALSO

521       perlguts and perlapi for internal information about magic.
522
523       perltie and overload for other ways of enhancing objects.
524

AUTHOR

526       Vincent Pit, "<perl at profvince.com>", <http://www.profvince.com>.
527
528       You can contact me by mail or on "irc.perl.org" (vincent).
529

BUGS

531       Please report any bugs or feature requests to "bug-variable-magic at
532       rt.cpan.org", or through the web interface at
533       http://rt.cpan.org/NoAuth/ReportBug.html?Queue=Variable-Magic
534       <http://rt.cpan.org/NoAuth/ReportBug.html?Queue=Variable-Magic>. I will
535       be notified, and then you'll automatically be notified of progress on
536       your bug as I make changes.
537

SUPPORT

539       You can find documentation for this module with the perldoc command.
540
541           perldoc Variable::Magic
542
543       Tests code coverage report is available at
544       http://www.profvince.com/perl/cover/Variable-Magic
545       <http://www.profvince.com/perl/cover/Variable-Magic>.
546
548       Copyright 2007,2008,2009,2010 Vincent Pit, all rights reserved.
549
550       This program is free software; you can redistribute it and/or modify it
551       under the same terms as Perl itself.
552
553
554
555perl v5.12.1                      2010-06-25                Variable::Magic(3)
Impressum