]> git.vpit.fr Git - perl/modules/Variable-Magic.git/blob - README
This is 0.25
[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.25
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 let the user add
19     extra data to any variable and hook syntaxical operations (such as
20     access, assignation or destruction) that can be applied to it. With this
21     module, you can add your own magic to any variable without the pain of
22     the C API.
23
24     Magic differs from tieing and overloading in several ways :
25
26     *   Magic isn't copied on assignation (as for blessed references) : you
27         attach it to variables, not values.
28
29     *   It doesn't replace the original semantics : magic callbacks trigger
30         before the original action take place, and can't prevent it to
31         happen.
32
33     *   It's mostly invisible at the Perl level : magical and non-magical
34         variables cannot be distinguished with "ref", "reftype" or another
35         trick.
36
37     *   It's notably faster, since perl's way of handling magic is lighter
38         by nature, and there's no need for any method resolution.
39
40     The operations that can be overloaded are :
41
42     *   "get"
43
44         This magic is invoked when the variable is evaluated (does not
45         include array/hash subscripts and slices).
46
47     *   "set"
48
49         This one is triggered each time the value of the variable changes
50         (includes array/hash subscripts and slices).
51
52     *   "len"
53
54         This magic is a little special : it is called when the 'size' or the
55         'length' of the variable has to be known by Perl. Typically, it's
56         the magic involved when an array is evaluated in scalar context, but
57         also on array assignation and loops ("for", "map" or "grep"). The
58         callback has then to return the length as an integer.
59
60     *   "clear"
61
62         This magic is invoked when the variable is reset, such as when an
63         array is emptied. Please note that this is different from undefining
64         the variable, even though the magic is called when the clearing is a
65         result of the undefine (e.g. for an array, but actually a bug
66         prevent it to work before perl 5.9.5 - see the history).
67
68     *   "free"
69
70         This one can be considered as an object destructor. It happens when
71         the variable goes out of scope (with the exception of global scope),
72         but not when it is undefined.
73
74     *   "copy"
75
76         This magic only applies to tied arrays and hashes. It fires when you
77         try to access or change their elements. It is available on your perl
78         iff "MGf_COPY" is true.
79
80     *   "dup"
81
82         Invoked when the variable is cloned across threads. Currently not
83         available.
84
85     *   "local"
86
87         When this magic is set on a variable, all subsequent localizations
88         of the variable will trigger the callback. It is available on your
89         perl iff "MGf_LOCAL" is true.
90
91     The following actions only apply to hashes and are available iff
92     "VMG_UVAR" is true. They are referred to as "uvar" magics.
93
94     *   "fetch"
95
96         This magic happens each time an element is fetched from the hash.
97
98     *   "store"
99
100         This one is called when an element is stored into the hash.
101
102     *   "exists"
103
104         This magic fires when a key is tested for existence in the hash.
105
106     *   "delete"
107
108         This last one triggers when a key is deleted in the hash, regardless
109         of whether the key actually exists in it.
110
111     You can refer to the tests to have more insight of where the different
112     magics are invoked.
113
114     To prevent any clash between different magics defined with this module,
115     an unique numerical signature is attached to each kind of magic (i.e.
116     each set of callbacks for magic operations).
117
118 PERL MAGIC HISTORY
119     The places where magic is invoked have changed a bit through perl
120     history. Here's a little list of the most recent ones.
121
122     *   5.6.x
123
124         *p14416* : 'copy' and 'dup' magic.
125
126     *   5.9.3
127
128         *p25854* : 'len' magic is no longer called when pushing an element
129         into a magic array.
130
131         *p26569* : 'local' magic.
132
133     *   5.9.5
134
135         *p31064* : Meaningful 'uvar' magic.
136
137         *p31473* : 'clear' magic wasn't invoked when undefining an array.
138         The bug is fixed as of this version.
139
140     *   5.10.0
141
142         Since "PERL_MAGIC_uvar" is uppercased, "hv_magic_check()" triggers
143         'copy' magic on hash stores for (non-tied) hashes that also have
144         'uvar' magic.
145
146     *   5.11.x
147
148         *p32969* : 'len' magic is no longer invoked when calling "length"
149         with a magical scalar.
150
151 CONSTANTS
152   "SIG_MIN"
153     The minimum integer used as a signature for user-defined magic.
154
155   "SIG_MAX"
156     The maximum integer used as a signature for user-defined magic.
157
158   "SIG_NBR"
159         SIG_NBR = SIG_MAX - SIG_MIN + 1
160
161   "MGf_COPY"
162     Evaluates to true iff the 'copy' magic is available.
163
164   "MGf_DUP"
165     Evaluates to true iff the 'dup' magic is available.
166
167   "MGf_LOCAL"
168     Evaluates to true iff the 'local' magic is available.
169
170   "VMG_UVAR"
171     When this constant is true, you can use the "fetch,store,exists,delete"
172     callbacks on hashes.
173
174   "VMG_COMPAT_ARRAY_PUSH_NOLEN"
175     True for perls that don't call 'len' magic when you push an element in a
176     magical array.
177
178   "VMG_COMPAT_ARRAY_UNDEF_CLEAR"
179     True for perls that call 'clear' magic when undefining magical arrays.
180
181   "VMG_COMPAT_SCALAR_LENGTH_NOLEN"
182     True for perls that don't call 'len' magic when taking the "length" of a
183     magical scalar.
184
185   "VMG_PERL_PATCHLEVEL"
186     The perl patchlevel this module was built with, or 0 for non-debugging
187     perls.
188
189   "VMG_THREADSAFE"
190     True iff this module could have been built with thread-safety features
191     enabled.
192
193 FUNCTIONS
194   "wizard"
195         wizard sig    => ...,
196                data   => sub { ... },
197                get    => sub { my ($ref, $data) = @_; ... },
198                set    => sub { my ($ref, $data) = @_; ... },
199                len    => sub { my ($ref, $data, $len) = @_; ... ; return $newlen; },
200                clear  => sub { my ($ref, $data) = @_; ... },
201                free   => sub { my ($ref, $data) = @_, ... },
202                copy   => sub { my ($ref, $data, $key, $elt) = @_; ... },
203                local  => sub { my ($ref, $data) = @_; ... },
204                fetch  => sub { my ($ref, $data, $key) = @_; ... },
205                store  => sub { my ($ref, $data, $key) = @_; ... },
206                exists => sub { my ($ref, $data, $key) = @_; ... },
207                delete => sub { my ($ref, $data, $key) = @_; ... }
208
209     This function creates a 'wizard', an opaque type that holds the magic
210     information. It takes a list of keys / values as argument, whose keys
211     can be :
212
213     *   "sig"
214
215         The numerical signature. If not specified or undefined, a random
216         signature is generated. If the signature matches an already defined
217         magic, then the existant magic object is returned.
218
219     *   "data"
220
221         A code reference to a private data constructor. It is called each
222         time this magic is cast on a variable, and the scalar returned is
223         used as private data storage for it. $_[0] is a reference to the
224         magic object and @_[1 .. @_-1] are all extra arguments that were
225         passed to "cast".
226
227     *   "get", "set", "len", "clear", "free", "copy", "local", "fetch",
228         "store", "exists" and "delete"
229
230         Code references to corresponding magic callbacks. You don't have to
231         specify all of them : the magic associated with undefined entries
232         simply won't be hooked. In those callbacks, $_[0] is always a
233         reference to the magic object and $_[1] is always the private data
234         (or "undef" when no private data constructor was supplied). In the
235         special case of "len" magic and when the variable is an array, $_[2]
236         contains its normal length. $_[2] is the current key in "copy",
237         "fetch", "store", "exists" and "delete" callbacks, although for
238         "copy" it may just be a copy of the actual key so it's useless to
239         (for example) cast magic on it. "copy" magic also receives the
240         current element (i.e. the value) in $_[3].
241
242         # A simple scalar tracer
243         my $wiz = wizard get  => sub { print STDERR "got ${$_[0]}\n" },
244                          set  => sub { print STDERR "set to ${$_[0]}\n" },
245                          free => sub { print STDERR "${$_[0]} was deleted\n" }
246
247   "gensig"
248     With this tool, you can manually generate random magic signature between
249     SIG_MIN and SIG_MAX inclusive. That's the way "wizard" creates them when
250     no signature is supplied.
251
252         # Generate a signature
253         my $sig = gensig;
254
255   "getsig"
256         getsig $wiz
257
258     This accessor returns the magic signature of this wizard.
259
260         # Get $wiz signature
261         my $sig = getsig $wiz;
262
263   "cast"
264         cast [$@%&*]var, [$wiz|$sig], ...
265
266     This function associates $wiz magic to the variable supplied, without
267     overwriting any other kind of magic. You can also supply the numeric
268     signature $sig instead of $wiz. It returns true on success or when $wiz
269     magic is already present, 0 on error, and "undef" when no magic
270     corresponds to the given signature (in case $sig was supplied). All
271     extra arguments specified after $wiz are passed to the private data
272     constructor. If the variable isn't a hash, any "uvar" callback of the
273     wizard is safely ignored.
274
275         # Casts $wiz onto $x. If $wiz isn't a signature, undef can't be returned.
276         my $x;
277         die 'error' unless cast $x, $wiz;
278
279   "getdata"
280         getdata [$@%&*]var, [$wiz|$sig]
281
282     This accessor fetches the private data associated with the magic $wiz
283     (or the signature $sig) in the variable. "undef" is returned when no
284     such magic or data is found, or when $sig does not represent a current
285     valid magic object.
286
287         # Get the attached data.
288         my $data = getdata $x, $wiz or die 'no such magic or magic has no data';
289
290   "dispell"
291         dispell [$@%&*]variable, [$wiz|$sig]
292
293     The exact opposite of "cast" : it dissociates $wiz magic from the
294     variable. You can also pass the magic signature $sig as the second
295     argument. True is returned on success, 0 on error or when no magic
296     represented by $wiz could be found in the variable, and "undef" when no
297     magic corresponds to the given signature (in case $sig was supplied).
298
299         # Dispell now. If $wiz isn't a signature, undef can't be returned.
300         die 'no such magic or error' unless dispell $x, $wiz;
301
302 EXPORT
303     The functions "wizard", "gensig", "getsig", "cast", "getdata" and
304     "dispell" are only exported on request. All of them are exported by the
305     tags ':funcs' and ':all'.
306
307     The constants "SIG_MIN", "SIG_MAX", "SIG_NBR", "MGf_COPY", "MGf_DUP",
308     "MGf_LOCAL" and "VMG_UVAR" are also only exported on request. They are
309     all exported by the tags ':consts' and ':all'.
310
311 CAVEATS
312     If you store a magic object in the private data slot, the magic won't be
313     accessible by "getdata" since it's not copied by assignation. The only
314     way to address this would be to return a reference.
315
316     If you define a wizard with a "free" callback and cast it on itself,
317     this destructor won't be called because the wizard will be destroyed
318     first.
319
320 DEPENDENCIES
321     perl 5.7.3.
322
323     Carp (standard since perl 5), XSLoader (standard since perl 5.006).
324
325     Copy tests need Tie::Array (standard since perl 5.005) and Tie::Hash
326     (since 5.002).
327
328     Some uvar tests need Hash::Util::FieldHash (standard since perl
329     5.009004).
330
331     Glob tests need Symbol (standard since perl 5.002).
332
333     Threads tests need threads and threads::shared.
334
335 SEE ALSO
336     perlguts and perlapi for internal information about magic.
337
338     perltie and overload for other ways of enhancing objects.
339
340 AUTHOR
341     Vincent Pit, "<perl at profvince.com>", <http://www.profvince.com>.
342
343     You can contact me by mail or on "irc.perl.org" (vincent).
344
345 BUGS
346     Please report any bugs or feature requests to "bug-variable-magic at
347     rt.cpan.org", or through the web interface at
348     <http://rt.cpan.org/NoAuth/ReportBug.html?Queue=Variable-Magic>. I will
349     be notified, and then you'll automatically be notified of progress on
350     your bug as I make changes.
351
352 SUPPORT
353     You can find documentation for this module with the perldoc command.
354
355         perldoc Variable::Magic
356
357     Tests code coverage report is available at
358     <http://www.profvince.com/perl/cover/Variable-Magic>.
359
360 COPYRIGHT & LICENSE
361     Copyright 2007-2008 Vincent Pit, all rights reserved.
362
363     This program is free software; you can redistribute it and/or modify it
364     under the same terms as Perl itself.
365