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 1.03 of Attribute::Handlers.
10
12 package MyClass;
13 require 5.006;
14 use Attribute::Handlers;
15 no warnings 'redefine';
16
17
18 sub Good : ATTR(SCALAR) {
19 my ($package, $symbol, $referent, $attr, $data) = @_;
20
21 # Invoked for any scalar variable with a :Good attribute,
22 # provided the variable was declared in MyClass (or
23 # a derived class) or typed to MyClass.
24
25 # Do whatever to $referent here (executed in CHECK phase).
26 ...
27 }
28
29 sub Bad : ATTR(SCALAR) {
30 # Invoked for any scalar variable with a :Bad attribute,
31 # provided the variable was declared in MyClass (or
32 # a derived class) or typed to MyClass.
33 ...
34 }
35
36 sub Good : ATTR(ARRAY) {
37 # Invoked for any array variable with a :Good attribute,
38 # provided the variable was declared in MyClass (or
39 # a derived class) or typed to MyClass.
40 ...
41 }
42
43 sub Good : ATTR(HASH) {
44 # Invoked for any hash variable with a :Good attribute,
45 # provided the variable was declared in MyClass (or
46 # a derived class) or typed to MyClass.
47 ...
48 }
49
50 sub Ugly : ATTR(CODE) {
51 # Invoked for any subroutine declared in MyClass (or a
52 # derived class) with an :Ugly attribute.
53 ...
54 }
55
56 sub Omni : ATTR {
57 # Invoked for any scalar, array, hash, or subroutine
58 # with an :Omni attribute, provided the variable or
59 # subroutine was declared in MyClass (or a derived class)
60 # or the variable was typed to MyClass.
61 # Use ref($_[2]) to determine what kind of referent it was.
62 ...
63 }
64
65
66 use Attribute::Handlers autotie => { Cycle => Tie::Cycle };
67
68 my $next : Cycle(['A'..'Z']);
69
71 This module, when inherited by a package, allows that package's class
72 to define attribute handler subroutines for specific attributes.
73 Variables and subroutines subsequently defined in that package, or in
74 packages derived from that package may be given attributes with the
75 same names as the attribute handler subroutines, which will then be
76 called in one of the compilation phases (i.e. in a "BEGIN", "CHECK",
77 "INIT", or "END" block). ("UNITCHECK" blocks don't correspond to a
78 global compilation phase, so they can't be specified here.)
79
80 To create a handler, define it as a subroutine with the same name as
81 the desired attribute, and declare the subroutine itself with the
82 attribute ":ATTR". For example:
83
84 package LoudDecl;
85 use Attribute::Handlers;
86
87 sub Loud :ATTR {
88 my ($package, $symbol, $referent, $attr, $data, $phase,
89 $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 usable form before passing it to the handler (but
158 see "Non-interpretive attribute handlers"). If those efforts succeed,
159 the interpreted data is passed in an array reference; if they fail, the
160 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/till, 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 usable 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
344 Note that we now have to pass the cycling values as an array reference,
345 since the "autotie" mechanism passes "tie" a list of arguments as a
346 list (as in the Tie::Whatever example), not as an array reference (as
347 in the original Tie::Cycle example at the start of this section).
348
349 The argument after 'autotie' is a reference to a hash in which each key
350 is the name of an attribute to be created, and each value is the class
351 to which variables ascribed that attribute should be tied.
352
353 Note that there is no longer any need to import the Tie::Cycle module
354 -- Attribute::Handlers takes care of that automagically. You can even
355 pass arguments to the module's "import" subroutine, by appending them
356 to the class name. For example:
357
358 use Attribute::Handlers
359 autotie => { Dir => 'Tie::Dir qw(DIR_UNLINK)' };
360
361 If the attribute name is unqualified, the attribute is installed in the
362 current package. Otherwise it is installed in the qualifier's package:
363
364 package Here;
365
366 use Attribute::Handlers autotie => {
367 Other::Good => Tie::SecureHash, # tie attr installed in Other::
368 Bad => Tie::Taxes, # tie attr installed in Here::
369 UNIVERSAL::Ugly => Software::Patent # tie attr installed everywhere
370 };
371
372 Autoties are most commonly used in the module to which they actually
373 tie, and need to export their attributes to any module that calls them.
374 To facilitate this, Attribute::Handlers recognizes a special "pseudo-
375 class" -- "__CALLER__", which may be specified as the qualifier of an
376 attribute:
377
378 package Tie::Me::Kangaroo::Down::Sport;
379
380 use Attribute::Handlers autotie =>
381 { '__CALLER__::Roo' => __PACKAGE__ };
382
383 This causes Attribute::Handlers to define the "Roo" attribute in the
384 package that imports the Tie::Me::Kangaroo::Down::Sport module.
385
386 Note that it is important to quote the __CALLER__::Roo identifier
387 because a bug in perl 5.8 will refuse to parse it and cause an unknown
388 error.
389
390 Passing the tied object to "tie"
391
392 Occasionally it is important to pass a reference to the object being
393 tied to the TIESCALAR, TIEHASH, etc. that ties it.
394
395 The "autotie" mechanism supports this too. The following code:
396
397 use Attribute::Handlers autotieref => { Selfish => Tie::Selfish };
398 my $var : Selfish(@args);
399
400 has the same effect as:
401
402 tie my $var, 'Tie::Selfish', @args;
403
404 But when "autotieref" is used instead of "autotie":
405
406 use Attribute::Handlers autotieref => { Selfish => Tie::Selfish };
407 my $var : Selfish(@args);
408
409 the effect is to pass the "tie" call an extra reference to the variable
410 being tied:
411
412 tie my $var, 'Tie::Selfish', \$var, @args;
413
415 If the class shown in "SYNOPSIS" were placed in the MyClass.pm module,
416 then the following code:
417
418 package main;
419 use MyClass;
420
421 my MyClass $slr :Good :Bad(1**1-1) :Omni(-vorous);
422
423 package SomeOtherClass;
424 use base MyClass;
425
426 sub tent { 'acle' }
427
428 sub fn :Ugly(sister) :Omni('po',tent()) {...}
429 my @arr :Good :Omni(s/cie/nt/);
430 my %hsh :Good(q/bye/) :Omni(q/bus/);
431
432 would cause the following handlers to be invoked:
433
434 # my MyClass $slr :Good :Bad(1**1-1) :Omni(-vorous);
435
436 MyClass::Good:ATTR(SCALAR)( 'MyClass', # class
437 'LEXICAL', # no typeglob
438 \$slr, # referent
439 'Good', # attr name
440 undef # no attr data
441 'CHECK', # compiler phase
442 );
443
444 MyClass::Bad:ATTR(SCALAR)( 'MyClass', # class
445 'LEXICAL', # no typeglob
446 \$slr, # referent
447 'Bad', # attr name
448 0 # eval'd attr data
449 'CHECK', # compiler phase
450 );
451
452 MyClass::Omni:ATTR(SCALAR)( 'MyClass', # class
453 'LEXICAL', # no typeglob
454 \$slr, # referent
455 'Omni', # attr name
456 '-vorous' # eval'd attr data
457 'CHECK', # compiler phase
458 );
459
460
461 # sub fn :Ugly(sister) :Omni('po',tent()) {...}
462
463 MyClass::UGLY:ATTR(CODE)( 'SomeOtherClass', # class
464 \*SomeOtherClass::fn, # typeglob
465 \&SomeOtherClass::fn, # referent
466 'Ugly', # attr name
467 'sister' # eval'd attr data
468 'CHECK', # compiler phase
469 );
470
471 MyClass::Omni:ATTR(CODE)( 'SomeOtherClass', # class
472 \*SomeOtherClass::fn, # typeglob
473 \&SomeOtherClass::fn, # referent
474 'Omni', # attr name
475 ['po','acle'] # eval'd attr data
476 'CHECK', # compiler phase
477 );
478
479
480 # my @arr :Good :Omni(s/cie/nt/);
481
482 MyClass::Good:ATTR(ARRAY)( 'SomeOtherClass', # class
483 'LEXICAL', # no typeglob
484 \@arr, # referent
485 'Good', # attr name
486 undef # no attr data
487 'CHECK', # compiler phase
488 );
489
490 MyClass::Omni:ATTR(ARRAY)( 'SomeOtherClass', # class
491 'LEXICAL', # no typeglob
492 \@arr, # referent
493 'Omni', # attr name
494 "" # eval'd attr data
495 'CHECK', # compiler phase
496 );
497
498
499 # my %hsh :Good(q/bye) :Omni(q/bus/);
500
501 MyClass::Good:ATTR(HASH)( 'SomeOtherClass', # class
502 'LEXICAL', # no typeglob
503 \%hsh, # referent
504 'Good', # attr name
505 'q/bye' # raw attr data
506 'CHECK', # compiler phase
507 );
508
509 MyClass::Omni:ATTR(HASH)( 'SomeOtherClass', # class
510 'LEXICAL', # no typeglob
511 \%hsh, # referent
512 'Omni', # attr name
513 'bus' # eval'd attr data
514 'CHECK', # compiler phase
515 );
516
517 Installing handlers into UNIVERSAL, makes them...err..universal. For
518 example:
519
520 package Descriptions;
521 use Attribute::Handlers;
522
523 my %name;
524 sub name { return $name{$_[2]}||*{$_[1]}{NAME} }
525
526 sub UNIVERSAL::Name :ATTR {
527 $name{$_[2]} = $_[4];
528 }
529
530 sub UNIVERSAL::Purpose :ATTR {
531 print STDERR "Purpose of ", &name, " is $_[4]\n";
532 }
533
534 sub UNIVERSAL::Unit :ATTR {
535 print STDERR &name, " measured in $_[4]\n";
536 }
537
538 Let's you write:
539
540 use Descriptions;
541
542 my $capacity : Name(capacity)
543 : Purpose(to store max storage capacity for files)
544 : Unit(Gb);
545
546
547 package Other;
548
549 sub foo : Purpose(to foo all data before barring it) { }
550
551 # etc.
552
554 This module offers a single utility function, findsym().
555
556 findsym
557 my $symbol = Attribute::Handlers::findsym($package, $referent);
558
559 The function looks in the symbol table of $package for the typeglob
560 for $referent, which is a reference to a variable or subroutine
561 (SCALAR, ARRAY, HASH, or CODE). If it finds the typeglob, it
562 returns it. Otherwise, it returns undef. Note that "findsym"
563 memoizes the typeglobs it has previously successfully found, so
564 subsequent calls with the same arguments should be much faster.
565
567 "Bad attribute type: ATTR(%s)"
568 An attribute handler was specified with an :ATTR(ref_type), but the
569 type of referent it was defined to handle wasn't one of the five
570 permitted: "SCALAR", "ARRAY", "HASH", "CODE", or "ANY".
571
572 "Attribute handler %s doesn't handle %s attributes"
573 A handler for attributes of the specified name was defined, but not
574 for the specified type of declaration. Typically encountered when
575 trying to apply a "VAR" attribute handler to a subroutine, or a
576 "SCALAR" attribute handler to some other type of variable.
577
578 "Declaration of %s attribute in package %s may clash with future
579 reserved word"
580 A handler for an attributes with an all-lowercase name was
581 declared. An attribute with an all-lowercase name might have a
582 meaning to Perl itself some day, even though most don't yet. Use a
583 mixed-case attribute name, instead.
584
585 "Can't have two ATTR specifiers on one subroutine"
586 You just can't, okay? Instead, put all the specifications together
587 with commas between them in a single ATTR(specification).
588
589 "Can't autotie a %s"
590 You can only declare autoties for types "SCALAR", "ARRAY", and
591 "HASH". They're the only things (apart from typeglobs -- which are
592 not declarable) that Perl can tie.
593
594 "Internal error: %s symbol went missing"
595 Something is rotten in the state of the program. An attributed
596 subroutine ceased to exist between the point it was declared and
597 the point at which its attribute handler(s) would have been called.
598
599 "Won't be able to apply END handler"
600 You have defined an END handler for an attribute that is being
601 applied to a lexical variable. Since the variable may not be
602 available during END this won't happen.
603
605 Damian Conway (damian@conway.org). The maintainer of this module is now
606 Rafael Garcia-Suarez (rgarciasuarez@gmail.com).
607
608 Maintainer of the CPAN release is Steffen Mueller (smueller@cpan.org).
609 Contact him with technical difficulties with respect to the packaging
610 of the CPAN module.
611
613 There are undoubtedly serious bugs lurking somewhere in code this funky
614 :-) Bug reports and other feedback are most welcome.
615
617 Copyright (c) 2001-2014, Damian Conway. All Rights Reserved.
618 This module is free software. It may be used, redistributed
619 and/or modified under the same terms as Perl itself.
620
621
622
623perl v5.38.2 2023-11-30 Attribute::Handlers(3pm)