1Attribute::Handlers(3pm)Perl Programmers Reference GuideAttribute::Handlers(3pm)
2
3
4
6 Attribute::Handlers - Simpler definition of attribute handlers
7
9 This document describes version 0.87 of Attribute::Handlers, released
10 September 21, 2009.
11
13 package MyClass;
14 require 5.006;
15 use Attribute::Handlers;
16 no warnings 'redefine';
17
18
19 sub Good : ATTR(SCALAR) {
20 my ($package, $symbol, $referent, $attr, $data) = @_;
21
22 # Invoked for any scalar variable with a :Good attribute,
23 # provided the variable was declared in MyClass (or
24 # a derived class) or typed to MyClass.
25
26 # Do whatever to $referent here (executed in CHECK phase).
27 ...
28 }
29
30 sub Bad : ATTR(SCALAR) {
31 # Invoked for any scalar variable with a :Bad attribute,
32 # provided the variable was declared in MyClass (or
33 # a derived class) or typed to MyClass.
34 ...
35 }
36
37 sub Good : ATTR(ARRAY) {
38 # Invoked for any array variable with a :Good attribute,
39 # provided the variable was declared in MyClass (or
40 # a derived class) or typed to MyClass.
41 ...
42 }
43
44 sub Good : ATTR(HASH) {
45 # Invoked for any hash variable with a :Good attribute,
46 # provided the variable was declared in MyClass (or
47 # a derived class) or typed to MyClass.
48 ...
49 }
50
51 sub Ugly : ATTR(CODE) {
52 # Invoked for any subroutine declared in MyClass (or a
53 # derived class) with an :Ugly attribute.
54 ...
55 }
56
57 sub Omni : ATTR {
58 # Invoked for any scalar, array, hash, or subroutine
59 # with an :Omni attribute, provided the variable or
60 # subroutine was declared in MyClass (or a derived class)
61 # or the variable was typed to MyClass.
62 # Use ref($_[2]) to determine what kind of referent it was.
63 ...
64 }
65
66
67 use Attribute::Handlers autotie => { Cycle => Tie::Cycle };
68
69 my $next : Cycle(['A'..'Z']);
70
72 This module, when inherited by a package, allows that package's class
73 to define attribute handler subroutines for specific attributes.
74 Variables and subroutines subsequently defined in that package, or in
75 packages derived from that package may be given attributes with the
76 same names as the attribute handler subroutines, which will then be
77 called in one of the compilation phases (i.e. in a "BEGIN", "CHECK",
78 "INIT", or "END" block). ("UNITCHECK" blocks don't correspond to a
79 global compilation phase, so they can't be specified here.)
80
81 To create a handler, define it as a subroutine with the same name as
82 the desired attribute, and declare the subroutine itself with the
83 attribute ":ATTR". For example:
84
85 package LoudDecl;
86 use Attribute::Handlers;
87
88 sub Loud :ATTR {
89 my ($package, $symbol, $referent, $attr, $data, $phase, $filename, $linenum) = @_;
90 print STDERR
91 ref($referent), " ",
92 *{$symbol}{NAME}, " ",
93 "($referent) ", "was just declared ",
94 "and ascribed the ${attr} attribute ",
95 "with data ($data)\n",
96 "in phase $phase\n",
97 "in file $filename at line $linenum\n";
98 }
99
100 This creates a handler for the attribute ":Loud" in the class LoudDecl.
101 Thereafter, any subroutine declared with a ":Loud" attribute in the
102 class LoudDecl:
103
104 package LoudDecl;
105
106 sub foo: Loud {...}
107
108 causes the above handler to be invoked, and passed:
109
110 [0] the name of the package into which it was declared;
111
112 [1] a reference to the symbol table entry (typeglob) containing the
113 subroutine;
114
115 [2] a reference to the subroutine;
116
117 [3] the name of the attribute;
118
119 [4] any data associated with that attribute;
120
121 [5] the name of the phase in which the handler is being invoked;
122
123 [6] the filename in which the handler is being invoked;
124
125 [7] the line number in this file.
126
127 Likewise, declaring any variables with the ":Loud" attribute within the
128 package:
129
130 package LoudDecl;
131
132 my $foo :Loud;
133 my @foo :Loud;
134 my %foo :Loud;
135
136 will cause the handler to be called with a similar argument list
137 (except, of course, that $_[2] will be a reference to the variable).
138
139 The package name argument will typically be the name of the class into
140 which the subroutine was declared, but it may also be the name of a
141 derived class (since handlers are inherited).
142
143 If a lexical variable is given an attribute, there is no symbol table
144 to which it belongs, so the symbol table argument ($_[1]) is set to the
145 string 'LEXICAL' in that case. Likewise, ascribing an attribute to an
146 anonymous subroutine results in a symbol table argument of 'ANON'.
147
148 The data argument passes in the value (if any) associated with the
149 attribute. For example, if &foo had been declared:
150
151 sub foo :Loud("turn it up to 11, man!") {...}
152
153 then a reference to an array containing the string "turn it up to 11,
154 man!" would be passed as the last argument.
155
156 Attribute::Handlers makes strenuous efforts to convert the data
157 argument ($_[4]) to a useable form before passing it to the handler
158 (but see "Non-interpretive attribute handlers"). If those efforts
159 succeed, the interpreted data is passed in an array reference; if they
160 fail, the raw data is passed as a string. For example, all of these:
161
162 sub foo :Loud(till=>ears=>are=>bleeding) {...}
163 sub foo :Loud(qw/till ears are bleeding/) {...}
164 sub foo :Loud(qw/my, ears, are, bleeding/) {...}
165 sub foo :Loud(till,ears,are,bleeding) {...}
166
167 causes it to pass "['till','ears','are','bleeding']" as the handler's
168 data argument. While:
169
170 sub foo :Loud(['till','ears','are','bleeding']) {...}
171
172 causes it to pass "[ ['till','ears','are','bleeding'] ]"; the array
173 reference specified in the data being passed inside the standard array
174 reference indicating successful interpretation.
175
176 However, if the data can't be parsed as valid Perl, then it is passed
177 as an uninterpreted string. For example:
178
179 sub foo :Loud(my,ears,are,bleeding) {...}
180 sub foo :Loud(qw/my ears are bleeding) {...}
181
182 cause the strings 'my,ears,are,bleeding' and 'qw/my ears are bleeding'
183 respectively to be passed as the data argument.
184
185 If no value is associated with the attribute, "undef" is passed.
186
187 Typed lexicals
188 Regardless of the package in which it is declared, if a lexical
189 variable is ascribed an attribute, the handler that is invoked is the
190 one belonging to the package to which it is typed. For example, the
191 following declarations:
192
193 package OtherClass;
194
195 my LoudDecl $loudobj : Loud;
196 my LoudDecl @loudobjs : Loud;
197 my LoudDecl %loudobjex : Loud;
198
199 causes the LoudDecl::Loud handler to be invoked (even if OtherClass
200 also defines a handler for ":Loud" attributes).
201
202 Type-specific attribute handlers
203 If an attribute handler is declared and the ":ATTR" specifier is given
204 the name of a built-in type ("SCALAR", "ARRAY", "HASH", or "CODE"), the
205 handler is only applied to declarations of that type. For example, the
206 following definition:
207
208 package LoudDecl;
209
210 sub RealLoud :ATTR(SCALAR) { print "Yeeeeow!" }
211
212 creates an attribute handler that applies only to scalars:
213
214 package Painful;
215 use base LoudDecl;
216
217 my $metal : RealLoud; # invokes &LoudDecl::RealLoud
218 my @metal : RealLoud; # error: unknown attribute
219 my %metal : RealLoud; # error: unknown attribute
220 sub metal : RealLoud {...} # error: unknown attribute
221
222 You can, of course, declare separate handlers for these types as well
223 (but you'll need to specify "no warnings 'redefine'" to do it quietly):
224
225 package LoudDecl;
226 use Attribute::Handlers;
227 no warnings 'redefine';
228
229 sub RealLoud :ATTR(SCALAR) { print "Yeeeeow!" }
230 sub RealLoud :ATTR(ARRAY) { print "Urrrrrrrrrr!" }
231 sub RealLoud :ATTR(HASH) { print "Arrrrrgggghhhhhh!" }
232 sub RealLoud :ATTR(CODE) { croak "Real loud sub torpedoed" }
233
234 You can also explicitly indicate that a single handler is meant to be
235 used for all types of referents like so:
236
237 package LoudDecl;
238 use Attribute::Handlers;
239
240 sub SeriousLoud :ATTR(ANY) { warn "Hearing loss imminent" }
241
242 (I.e. "ATTR(ANY)" is a synonym for ":ATTR").
243
244 Non-interpretive attribute handlers
245 Occasionally the strenuous efforts Attribute::Handlers makes to convert
246 the data argument ($_[4]) to a useable form before passing it to the
247 handler get in the way.
248
249 You can turn off that eagerness-to-help by declaring an attribute
250 handler with the keyword "RAWDATA". For example:
251
252 sub Raw : ATTR(RAWDATA) {...}
253 sub Nekkid : ATTR(SCALAR,RAWDATA) {...}
254 sub Au::Naturale : ATTR(RAWDATA,ANY) {...}
255
256 Then the handler makes absolutely no attempt to interpret the data it
257 receives and simply passes it as a string:
258
259 my $power : Raw(1..100); # handlers receives "1..100"
260
261 Phase-specific attribute handlers
262 By default, attribute handlers are called at the end of the compilation
263 phase (in a "CHECK" block). This seems to be optimal in most cases
264 because most things that can be defined are defined by that point but
265 nothing has been executed.
266
267 However, it is possible to set up attribute handlers that are called at
268 other points in the program's compilation or execution, by explicitly
269 stating the phase (or phases) in which you wish the attribute handler
270 to be called. For example:
271
272 sub Early :ATTR(SCALAR,BEGIN) {...}
273 sub Normal :ATTR(SCALAR,CHECK) {...}
274 sub Late :ATTR(SCALAR,INIT) {...}
275 sub Final :ATTR(SCALAR,END) {...}
276 sub Bookends :ATTR(SCALAR,BEGIN,END) {...}
277
278 As the last example indicates, a handler may be set up to be (re)called
279 in two or more phases. The phase name is passed as the handler's final
280 argument.
281
282 Note that attribute handlers that are scheduled for the "BEGIN" phase
283 are handled as soon as the attribute is detected (i.e. before any
284 subsequently defined "BEGIN" blocks are executed).
285
286 Attributes as "tie" interfaces
287 Attributes make an excellent and intuitive interface through which to
288 tie variables. For example:
289
290 use Attribute::Handlers;
291 use Tie::Cycle;
292
293 sub UNIVERSAL::Cycle : ATTR(SCALAR) {
294 my ($package, $symbol, $referent, $attr, $data, $phase) = @_;
295 $data = [ $data ] unless ref $data eq 'ARRAY';
296 tie $$referent, 'Tie::Cycle', $data;
297 }
298
299 # and thereafter...
300
301 package main;
302
303 my $next : Cycle('A'..'Z'); # $next is now a tied variable
304
305 while (<>) {
306 print $next;
307 }
308
309 Note that, because the "Cycle" attribute receives its arguments in the
310 $data variable, if the attribute is given a list of arguments, $data
311 will consist of a single array reference; otherwise, it will consist of
312 the single argument directly. Since Tie::Cycle requires its cycling
313 values to be passed as an array reference, this means that we need to
314 wrap non-array-reference arguments in an array constructor:
315
316 $data = [ $data ] unless ref $data eq 'ARRAY';
317
318 Typically, however, things are the other way around: the tieable class
319 expects its arguments as a flattened list, so the attribute looks like:
320
321 sub UNIVERSAL::Cycle : ATTR(SCALAR) {
322 my ($package, $symbol, $referent, $attr, $data, $phase) = @_;
323 my @data = ref $data eq 'ARRAY' ? @$data : $data;
324 tie $$referent, 'Tie::Whatever', @data;
325 }
326
327 This software pattern is so widely applicable that Attribute::Handlers
328 provides a way to automate it: specifying 'autotie' in the "use
329 Attribute::Handlers" statement. So, the cycling example, could also be
330 written:
331
332 use Attribute::Handlers autotie => { Cycle => 'Tie::Cycle' };
333
334 # and thereafter...
335
336 package main;
337
338 my $next : Cycle(['A'..'Z']); # $next is now a tied variable
339
340 while (<>) {
341 print $next;
342
343 Note that we now have to pass the cycling values as an array reference,
344 since the "autotie" mechanism passes "tie" a list of arguments as a
345 list (as in the Tie::Whatever example), not as an array reference (as
346 in the original Tie::Cycle example at the start of this section).
347
348 The argument after 'autotie' is a reference to a hash in which each key
349 is the name of an attribute to be created, and each value is the class
350 to which variables ascribed that attribute should be tied.
351
352 Note that there is no longer any need to import the Tie::Cycle module
353 -- Attribute::Handlers takes care of that automagically. You can even
354 pass arguments to the module's "import" subroutine, by appending them
355 to the class name. For example:
356
357 use Attribute::Handlers
358 autotie => { Dir => 'Tie::Dir qw(DIR_UNLINK)' };
359
360 If the attribute name is unqualified, the attribute is installed in the
361 current package. Otherwise it is installed in the qualifier's package:
362
363 package Here;
364
365 use Attribute::Handlers autotie => {
366 Other::Good => Tie::SecureHash, # tie attr installed in Other::
367 Bad => Tie::Taxes, # tie attr installed in Here::
368 UNIVERSAL::Ugly => Software::Patent # tie attr installed everywhere
369 };
370
371 Autoties are most commonly used in the module to which they actually
372 tie, and need to export their attributes to any module that calls them.
373 To facilitate this, Attribute::Handlers recognizes a special "pseudo-
374 class" -- "__CALLER__", which may be specified as the qualifier of an
375 attribute:
376
377 package Tie::Me::Kangaroo:Down::Sport;
378
379 use Attribute::Handlers autotie => { '__CALLER__::Roo' => __PACKAGE__ };
380
381 This causes Attribute::Handlers to define the "Roo" attribute in the
382 package that imports the Tie::Me::Kangaroo:Down::Sport module.
383
384 Note that it is important to quote the __CALLER__::Roo identifier
385 because a bug in perl 5.8 will refuse to parse it and cause an unknown
386 error.
387
388 Passing the tied object to "tie"
389
390 Occasionally it is important to pass a reference to the object being
391 tied to the TIESCALAR, TIEHASH, etc. that ties it.
392
393 The "autotie" mechanism supports this too. The following code:
394
395 use Attribute::Handlers autotieref => { Selfish => Tie::Selfish };
396 my $var : Selfish(@args);
397
398 has the same effect as:
399
400 tie my $var, 'Tie::Selfish', @args;
401
402 But when "autotieref" is used instead of "autotie":
403
404 use Attribute::Handlers autotieref => { Selfish => Tie::Selfish };
405 my $var : Selfish(@args);
406
407 the effect is to pass the "tie" call an extra reference to the variable
408 being tied:
409
410 tie my $var, 'Tie::Selfish', \$var, @args;
411
413 If the class shown in SYNOPSIS were placed in the MyClass.pm module,
414 then the following code:
415
416 package main;
417 use MyClass;
418
419 my MyClass $slr :Good :Bad(1**1-1) :Omni(-vorous);
420
421 package SomeOtherClass;
422 use base MyClass;
423
424 sub tent { 'acle' }
425
426 sub fn :Ugly(sister) :Omni('po',tent()) {...}
427 my @arr :Good :Omni(s/cie/nt/);
428 my %hsh :Good(q/bye/) :Omni(q/bus/);
429
430 would cause the following handlers to be invoked:
431
432 # my MyClass $slr :Good :Bad(1**1-1) :Omni(-vorous);
433
434 MyClass::Good:ATTR(SCALAR)( 'MyClass', # class
435 'LEXICAL', # no typeglob
436 \$slr, # referent
437 'Good', # attr name
438 undef # no attr data
439 'CHECK', # compiler phase
440 );
441
442 MyClass::Bad:ATTR(SCALAR)( 'MyClass', # class
443 'LEXICAL', # no typeglob
444 \$slr, # referent
445 'Bad', # attr name
446 0 # eval'd attr data
447 'CHECK', # compiler phase
448 );
449
450 MyClass::Omni:ATTR(SCALAR)( 'MyClass', # class
451 'LEXICAL', # no typeglob
452 \$slr, # referent
453 'Omni', # attr name
454 '-vorous' # eval'd attr data
455 'CHECK', # compiler phase
456 );
457
458
459 # sub fn :Ugly(sister) :Omni('po',tent()) {...}
460
461 MyClass::UGLY:ATTR(CODE)( 'SomeOtherClass', # class
462 \*SomeOtherClass::fn, # typeglob
463 \&SomeOtherClass::fn, # referent
464 'Ugly', # attr name
465 'sister' # eval'd attr data
466 'CHECK', # compiler phase
467 );
468
469 MyClass::Omni:ATTR(CODE)( 'SomeOtherClass', # class
470 \*SomeOtherClass::fn, # typeglob
471 \&SomeOtherClass::fn, # referent
472 'Omni', # attr name
473 ['po','acle'] # eval'd attr data
474 'CHECK', # compiler phase
475 );
476
477
478 # my @arr :Good :Omni(s/cie/nt/);
479
480 MyClass::Good:ATTR(ARRAY)( 'SomeOtherClass', # class
481 'LEXICAL', # no typeglob
482 \@arr, # referent
483 'Good', # attr name
484 undef # no attr data
485 'CHECK', # compiler phase
486 );
487
488 MyClass::Omni:ATTR(ARRAY)( 'SomeOtherClass', # class
489 'LEXICAL', # no typeglob
490 \@arr, # referent
491 'Omni', # attr name
492 "" # eval'd attr data
493 'CHECK', # compiler phase
494 );
495
496
497 # my %hsh :Good(q/bye) :Omni(q/bus/);
498
499 MyClass::Good:ATTR(HASH)( 'SomeOtherClass', # class
500 'LEXICAL', # no typeglob
501 \%hsh, # referent
502 'Good', # attr name
503 'q/bye' # raw attr data
504 'CHECK', # compiler phase
505 );
506
507 MyClass::Omni:ATTR(HASH)( 'SomeOtherClass', # class
508 'LEXICAL', # no typeglob
509 \%hsh, # referent
510 'Omni', # attr name
511 'bus' # eval'd attr data
512 'CHECK', # compiler phase
513 );
514
515 Installing handlers into UNIVERSAL, makes them...err..universal. For
516 example:
517
518 package Descriptions;
519 use Attribute::Handlers;
520
521 my %name;
522 sub name { return $name{$_[2]}||*{$_[1]}{NAME} }
523
524 sub UNIVERSAL::Name :ATTR {
525 $name{$_[2]} = $_[4];
526 }
527
528 sub UNIVERSAL::Purpose :ATTR {
529 print STDERR "Purpose of ", &name, " is $_[4]\n";
530 }
531
532 sub UNIVERSAL::Unit :ATTR {
533 print STDERR &name, " measured in $_[4]\n";
534 }
535
536 Let's you write:
537
538 use Descriptions;
539
540 my $capacity : Name(capacity)
541 : Purpose(to store max storage capacity for files)
542 : Unit(Gb);
543
544
545 package Other;
546
547 sub foo : Purpose(to foo all data before barring it) { }
548
549 # etc.
550
552 This module offers a single utility function, "findsym()".
553
554 findsym
555 my $symbol = Attribute::Handlers::findsym($package, $referent);
556
557 The function looks in the symbol table of $package for the typeglob
558 for $referent, which is a reference to a variable or subroutine
559 (SCALAR, ARRAY, HASH, or CODE). If it finds the typeglob, it
560 returns it. Otherwise, it returns undef. Note that "findsym"
561 memoizes the typeglobs it has previously successfully found, so
562 subsequent calls with the same arguments should be must faster.
563
565 "Bad attribute type: ATTR(%s)"
566 An attribute handler was specified with an ":ATTR(ref_type)", but
567 the type of referent it was defined to handle wasn't one of the
568 five permitted: "SCALAR", "ARRAY", "HASH", "CODE", or "ANY".
569
570 "Attribute handler %s doesn't handle %s attributes"
571 A handler for attributes of the specified name was defined, but not
572 for the specified type of declaration. Typically encountered whe
573 trying to apply a "VAR" attribute handler to a subroutine, or a
574 "SCALAR" attribute handler to some other type of variable.
575
576 "Declaration of %s attribute in package %s may clash with future
577 reserved word"
578 A handler for an attributes with an all-lowercase name was
579 declared. An attribute with an all-lowercase name might have a
580 meaning to Perl itself some day, even though most don't yet. Use a
581 mixed-case attribute name, instead.
582
583 "Can't have two ATTR specifiers on one subroutine"
584 You just can't, okay? Instead, put all the specifications together
585 with commas between them in a single "ATTR(specification)".
586
587 "Can't autotie a %s"
588 You can only declare autoties for types "SCALAR", "ARRAY", and
589 "HASH". They're the only things (apart from typeglobs -- which are
590 not declarable) that Perl can tie.
591
592 "Internal error: %s symbol went missing"
593 Something is rotten in the state of the program. An attributed
594 subroutine ceased to exist between the point it was declared and
595 the point at which its attribute handler(s) would have been called.
596
597 "Won't be able to apply END handler"
598 You have defined an END handler for an attribute that is being
599 applied to a lexical variable. Since the variable may not be
600 available during END this won't happen.
601
603 Damian Conway (damian@conway.org). The maintainer of this module is now
604 Rafael Garcia-Suarez (rgarciasuarez@gmail.com).
605
606 Maintainer of the CPAN release is Steffen Mueller (smueller@cpan.org).
607 Contact him with technical difficulties with respect to the packaging
608 of the CPAN module.
609
611 There are undoubtedly serious bugs lurking somewhere in code this funky
612 :-) Bug reports and other feedback are most welcome.
613
615 Copyright (c) 2001-2009, Damian Conway. All Rights Reserved.
616 This module is free software. It may be used, redistributed
617 and/or modified under the same terms as Perl itself.
618
619
620
621perl v5.12.4 2011-06-07 Attribute::Handlers(3pm)