Math::BigInt v1.87 take 6
[p5sagit/p5-mst-13.2.git] / lib / Attribute / Handlers.pm
CommitLineData
0e9b9e0c 1package Attribute::Handlers;
2use 5.006;
3use Carp;
4use warnings;
d6e4b61b 5use strict;
6use vars qw($VERSION $AUTOLOAD);
7$VERSION = '0.78_06';
0e9b9e0c 8# $DB::single=1;
9
10my %symcache;
11sub findsym {
12 my ($pkg, $ref, $type) = @_;
13 return $symcache{$pkg,$ref} if $symcache{$pkg,$ref};
14 $type ||= ref($ref);
15 my $found;
d6e4b61b 16 no strict 'refs';
0e9b9e0c 17 foreach my $sym ( values %{$pkg."::"} ) {
d6e4b61b 18 use strict;
39c882db 19 next unless ref ( \$sym ) eq 'GLOB';
0e9b9e0c 20 return $symcache{$pkg,$ref} = \$sym
21 if *{$sym}{$type} && *{$sym}{$type} == $ref;
22 }
23}
24
25my %validtype = (
26 VAR => [qw[SCALAR ARRAY HASH]],
27 ANY => [qw[SCALAR ARRAY HASH CODE]],
28 "" => [qw[SCALAR ARRAY HASH CODE]],
29 SCALAR => [qw[SCALAR]],
30 ARRAY => [qw[ARRAY]],
31 HASH => [qw[HASH]],
32 CODE => [qw[CODE]],
33);
34my %lastattr;
35my @declarations;
36my %raw;
37my %phase;
38my %sigil = (SCALAR=>'$', ARRAY=>'@', HASH=>'%');
39my $global_phase = 0;
40my %global_phases = (
41 BEGIN => 0,
42 CHECK => 1,
43 INIT => 2,
44 END => 3,
45);
46my @global_phases = qw(BEGIN CHECK INIT END);
47
48sub _usage_AH_ {
49 croak "Usage: use $_[0] autotie => {AttrName => TieClassName,...}";
50}
51
52my $qual_id = qr/^[_a-z]\w*(::[_a-z]\w*)*$/i;
53
54sub import {
55 my $class = shift @_;
56 return unless $class eq "Attribute::Handlers";
57 while (@_) {
58 my $cmd = shift;
59 if ($cmd =~ /^autotie((?:ref)?)$/) {
60 my $tiedata = ($1 ? '$ref, ' : '') . '@$data';
61 my $mapping = shift;
62 _usage_AH_ $class unless ref($mapping) eq 'HASH';
63 while (my($attr, $tieclass) = each %$mapping) {
64 $tieclass =~ s/^([_a-z]\w*(::[_a-z]\w*)*)(.*)/$1/is;
65 my $args = $3||'()';
66 _usage_AH_ $class unless $attr =~ $qual_id
67 && $tieclass =~ $qual_id
d6e4b61b 68 && eval "use base q\0$tieclass\0; 1";
0e9b9e0c 69 if ($tieclass->isa('Exporter')) {
70 local $Exporter::ExportLevel = 2;
71 $tieclass->import(eval $args);
72 }
73 $attr =~ s/__CALLER__/caller(1)/e;
74 $attr = caller()."::".$attr unless $attr =~ /::/;
75 eval qq{
76 sub $attr : ATTR(VAR) {
77 my (\$ref, \$data) = \@_[2,4];
78 my \$was_arrayref = ref \$data eq 'ARRAY';
79 \$data = [ \$data ] unless \$was_arrayref;
80 my \$type = ref(\$ref)||"value (".(\$ref||"<undef>").")";
81 (\$type eq 'SCALAR')? tie \$\$ref,'$tieclass',$tiedata
82 :(\$type eq 'ARRAY') ? tie \@\$ref,'$tieclass',$tiedata
83 :(\$type eq 'HASH') ? tie \%\$ref,'$tieclass',$tiedata
84 : die "Can't autotie a \$type\n"
85 } 1
86 } or die "Internal error: $@";
87 }
88 }
89 else {
90 croak "Can't understand $_";
91 }
92 }
93}
94sub _resolve_lastattr {
95 return unless $lastattr{ref};
96 my $sym = findsym @lastattr{'pkg','ref'}
97 or die "Internal error: $lastattr{pkg} symbol went missing";
98 my $name = *{$sym}{NAME};
99 warn "Declaration of $name attribute in package $lastattr{pkg} may clash with future reserved word\n"
100 if $^W and $name !~ /[A-Z]/;
101 foreach ( @{$validtype{$lastattr{type}}} ) {
d6e4b61b 102 no strict 'refs';
0e9b9e0c 103 *{"$lastattr{pkg}::_ATTR_${_}_${name}"} = $lastattr{ref};
104 }
105 %lastattr = ();
106}
107
108sub AUTOLOAD {
ac8e8084 109 return if $AUTOLOAD =~ /::DESTROY$/;
0e9b9e0c 110 my ($class) = $AUTOLOAD =~ m/(.*)::/g;
111 $AUTOLOAD =~ m/_ATTR_(.*?)_(.*)/ or
112 croak "Can't locate class method '$AUTOLOAD' via package '$class'";
4da5364c 113 croak "Attribute handler '$2' doesn't handle $1 attributes";
0e9b9e0c 114}
115
5ddc4af4 116my $builtin = qr/lvalue|method|locked|unique|shared/;
0e9b9e0c 117
118sub _gen_handler_AH_() {
119 return sub {
120 _resolve_lastattr;
121 my ($pkg, $ref, @attrs) = @_;
cab6c672 122 my (undef, $filename, $linenum) = caller 2;
0e9b9e0c 123 foreach (@attrs) {
124 my ($attr, $data) = /^([a-z_]\w*)(?:[(](.*)[)])?$/is or next;
125 if ($attr eq 'ATTR') {
d6e4b61b 126 no strict 'refs';
0e9b9e0c 127 $data ||= "ANY";
128 $raw{$ref} = $data =~ s/\s*,?\s*RAWDATA\s*,?\s*//;
129 $phase{$ref}{BEGIN} = 1
130 if $data =~ s/\s*,?\s*(BEGIN)\s*,?\s*//;
131 $phase{$ref}{INIT} = 1
132 if $data =~ s/\s*,?\s*(INIT)\s*,?\s*//;
133 $phase{$ref}{END} = 1
134 if $data =~ s/\s*,?\s*(END)\s*,?\s*//;
135 $phase{$ref}{CHECK} = 1
136 if $data =~ s/\s*,?\s*(CHECK)\s*,?\s*//
137 || ! keys %{$phase{$ref}};
138 # Added for cleanup to not pollute next call.
139 (%lastattr = ()),
140 croak "Can't have two ATTR specifiers on one subroutine"
141 if keys %lastattr;
142 croak "Bad attribute type: ATTR($data)"
143 unless $validtype{$data};
144 %lastattr=(pkg=>$pkg,ref=>$ref,type=>$data);
145 }
146 else {
c760c918 147 my $type = ref $ref;
148 my $handler = $pkg->can("_ATTR_${type}_${attr}");
0e9b9e0c 149 next unless $handler;
150 my $decl = [$pkg, $ref, $attr, $data,
cab6c672 151 $raw{$handler}, $phase{$handler}, $filename, $linenum];
0e9b9e0c 152 foreach my $gphase (@global_phases) {
153 _apply_handler_AH_($decl,$gphase)
154 if $global_phases{$gphase} <= $global_phase;
155 }
24952a9c 156 if ($global_phase != 0) {
157 # if _gen_handler_AH_ is being called after
158 # CHECK it's for a lexical, so make sure
159 # it didn't want to run anything later
160
161 local $Carp::CarpLevel = 2;
162 carp "Won't be able to apply END handler"
163 if $phase{$handler}{END};
164 }
165 else {
166 push @declarations, $decl
167 }
0e9b9e0c 168 }
169 $_ = undef;
170 }
171 return grep {defined && !/$builtin/} @attrs;
172 }
173}
174
d6e4b61b 175{
176 no strict 'refs';
177 *{"Attribute::Handlers::UNIVERSAL::MODIFY_${_}_ATTRIBUTES"} =
178 _gen_handler_AH_ foreach @{$validtype{ANY}};
179}
290b54b8 180push @UNIVERSAL::ISA, 'Attribute::Handlers::UNIVERSAL'
181 unless grep /^Attribute::Handlers::UNIVERSAL$/, @UNIVERSAL::ISA;
0e9b9e0c 182
183sub _apply_handler_AH_ {
184 my ($declaration, $phase) = @_;
cab6c672 185 my ($pkg, $ref, $attr, $data, $raw, $handlerphase, $filename, $linenum) = @$declaration;
0e9b9e0c 186 return unless $handlerphase->{$phase};
187 # print STDERR "Handling $attr on $ref in $phase with [$data]\n";
188 my $type = ref $ref;
189 my $handler = "_ATTR_${type}_${attr}";
190 my $sym = findsym($pkg, $ref);
191 $sym ||= $type eq 'CODE' ? 'ANON' : 'LEXICAL';
192 no warnings;
193 my $evaled = !$raw && eval("package $pkg; no warnings;
194 local \$SIG{__WARN__}=sub{die}; [$data]");
195 $data = ($evaled && $data =~ /^\s*\[/) ? [$evaled]
196 : ($evaled) ? $evaled
197 : [$data];
198 $pkg->$handler($sym,
199 (ref $sym eq 'GLOB' ? *{$sym}{ref $ref}||$ref : $ref),
200 $attr,
201 (@$data>1? $data : $data->[0]),
202 $phase,
cab6c672 203 $filename,
204 $linenum,
0e9b9e0c 205 );
206 return 1;
207}
208
ba690e32 209{
210 no warnings 'void';
211 CHECK {
212 $global_phase++;
213 _resolve_lastattr;
214 _apply_handler_AH_($_,'CHECK') foreach @declarations;
215 }
0e9b9e0c 216
ba690e32 217 INIT {
218 $global_phase++;
219 _apply_handler_AH_($_,'INIT') foreach @declarations
220 }
221}
0e9b9e0c 222
223END { $global_phase++; _apply_handler_AH_($_,'END') foreach @declarations }
224
2251;
226__END__
227
228=head1 NAME
229
230Attribute::Handlers - Simpler definition of attribute handlers
231
232=head1 VERSION
233
f903cfef 234This document describes version 0.78 of Attribute::Handlers,
235released October 5, 2002.
0e9b9e0c 236
237=head1 SYNOPSIS
238
239 package MyClass;
240 require v5.6.0;
241 use Attribute::Handlers;
242 no warnings 'redefine';
243
244
245 sub Good : ATTR(SCALAR) {
246 my ($package, $symbol, $referent, $attr, $data) = @_;
247
248 # Invoked for any scalar variable with a :Good attribute,
249 # provided the variable was declared in MyClass (or
250 # a derived class) or typed to MyClass.
251
252 # Do whatever to $referent here (executed in CHECK phase).
253 ...
254 }
255
256 sub Bad : ATTR(SCALAR) {
257 # Invoked for any scalar variable with a :Bad attribute,
258 # provided the variable was declared in MyClass (or
259 # a derived class) or typed to MyClass.
260 ...
261 }
262
263 sub Good : ATTR(ARRAY) {
264 # Invoked for any array variable with a :Good attribute,
265 # provided the variable was declared in MyClass (or
266 # a derived class) or typed to MyClass.
267 ...
268 }
269
270 sub Good : ATTR(HASH) {
271 # Invoked for any hash variable with a :Good attribute,
272 # provided the variable was declared in MyClass (or
273 # a derived class) or typed to MyClass.
274 ...
275 }
276
277 sub Ugly : ATTR(CODE) {
278 # Invoked for any subroutine declared in MyClass (or a
279 # derived class) with an :Ugly attribute.
280 ...
281 }
282
283 sub Omni : ATTR {
284 # Invoked for any scalar, array, hash, or subroutine
285 # with an :Omni attribute, provided the variable or
286 # subroutine was declared in MyClass (or a derived class)
287 # or the variable was typed to MyClass.
288 # Use ref($_[2]) to determine what kind of referent it was.
289 ...
290 }
291
292
293 use Attribute::Handlers autotie => { Cycle => Tie::Cycle };
294
295 my $next : Cycle(['A'..'Z']);
296
297
298=head1 DESCRIPTION
299
300This module, when inherited by a package, allows that package's class to
301define attribute handler subroutines for specific attributes. Variables
302and subroutines subsequently defined in that package, or in packages
303derived from that package may be given attributes with the same names as
304the attribute handler subroutines, which will then be called in one of
305the compilation phases (i.e. in a C<BEGIN>, C<CHECK>, C<INIT>, or C<END>
6d9eb87b 306block). (C<UNITCHECK> blocks don't correspond to a global compilation
307phase, so they can't be specified here.)
0e9b9e0c 308
309To create a handler, define it as a subroutine with the same name as
310the desired attribute, and declare the subroutine itself with the
311attribute C<:ATTR>. For example:
312
cab6c672 313 package LoudDecl;
314 use Attribute::Handlers;
315
316 sub Loud :ATTR {
317 my ($package, $symbol, $referent, $attr, $data, $phase, $filename, $linenum) = @_;
318 print STDERR
319 ref($referent), " ",
320 *{$symbol}{NAME}, " ",
321 "($referent) ", "was just declared ",
322 "and ascribed the ${attr} attribute ",
323 "with data ($data)\n",
324 "in phase $phase\n",
325 "in file $filename at line $linenum\n";
326 }
0e9b9e0c 327
328This creates a handler for the attribute C<:Loud> in the class LoudDecl.
329Thereafter, any subroutine declared with a C<:Loud> attribute in the class
330LoudDecl:
331
332 package LoudDecl;
333
334 sub foo: Loud {...}
335
336causes the above handler to be invoked, and passed:
337
338=over
339
340=item [0]
341
342the name of the package into which it was declared;
343
344=item [1]
345
346a reference to the symbol table entry (typeglob) containing the subroutine;
347
348=item [2]
349
350a reference to the subroutine;
351
352=item [3]
353
354the name of the attribute;
355
356=item [4]
357
358any data associated with that attribute;
359
360=item [5]
361
cab6c672 362the name of the phase in which the handler is being invoked;
363
364=item [6]
365
366the filename in which the handler is being invoked;
367
368=item [7]
369
370the line number in this file.
0e9b9e0c 371
372=back
373
374Likewise, declaring any variables with the C<:Loud> attribute within the
375package:
376
377 package LoudDecl;
378
379 my $foo :Loud;
380 my @foo :Loud;
381 my %foo :Loud;
382
383will cause the handler to be called with a similar argument list (except,
384of course, that C<$_[2]> will be a reference to the variable).
385
386The package name argument will typically be the name of the class into
387which the subroutine was declared, but it may also be the name of a derived
388class (since handlers are inherited).
389
390If a lexical variable is given an attribute, there is no symbol table to
391which it belongs, so the symbol table argument (C<$_[1]>) is set to the
392string C<'LEXICAL'> in that case. Likewise, ascribing an attribute to
393an anonymous subroutine results in a symbol table argument of C<'ANON'>.
394
395The data argument passes in the value (if any) associated with the
396attribute. For example, if C<&foo> had been declared:
397
398 sub foo :Loud("turn it up to 11, man!") {...}
399
400then the string C<"turn it up to 11, man!"> would be passed as the
401last argument.
402
403Attribute::Handlers makes strenuous efforts to convert
404the data argument (C<$_[4]>) to a useable form before passing it to
405the handler (but see L<"Non-interpretive attribute handlers">).
406For example, all of these:
407
408 sub foo :Loud(till=>ears=>are=>bleeding) {...}
409 sub foo :Loud(['till','ears','are','bleeding']) {...}
410 sub foo :Loud(qw/till ears are bleeding/) {...}
411 sub foo :Loud(qw/my, ears, are, bleeding/) {...}
412 sub foo :Loud(till,ears,are,bleeding) {...}
413
414causes it to pass C<['till','ears','are','bleeding']> as the handler's
415data argument. However, if the data can't be parsed as valid Perl, then
416it is passed as an uninterpreted string. For example:
417
418 sub foo :Loud(my,ears,are,bleeding) {...}
419 sub foo :Loud(qw/my ears are bleeding) {...}
420
421cause the strings C<'my,ears,are,bleeding'> and C<'qw/my ears are bleeding'>
422respectively to be passed as the data argument.
423
424If the attribute has only a single associated scalar data value, that value is
425passed as a scalar. If multiple values are associated, they are passed as an
426array reference. If no value is associated with the attribute, C<undef> is
427passed.
428
429
430=head2 Typed lexicals
431
432Regardless of the package in which it is declared, if a lexical variable is
433ascribed an attribute, the handler that is invoked is the one belonging to
434the package to which it is typed. For example, the following declarations:
435
436 package OtherClass;
437
438 my LoudDecl $loudobj : Loud;
439 my LoudDecl @loudobjs : Loud;
440 my LoudDecl %loudobjex : Loud;
441
442causes the LoudDecl::Loud handler to be invoked (even if OtherClass also
443defines a handler for C<:Loud> attributes).
444
445
446=head2 Type-specific attribute handlers
447
448If an attribute handler is declared and the C<:ATTR> specifier is
449given the name of a built-in type (C<SCALAR>, C<ARRAY>, C<HASH>, or C<CODE>),
450the handler is only applied to declarations of that type. For example,
451the following definition:
452
453 package LoudDecl;
454
455 sub RealLoud :ATTR(SCALAR) { print "Yeeeeow!" }
456
457creates an attribute handler that applies only to scalars:
458
459
460 package Painful;
461 use base LoudDecl;
462
463 my $metal : RealLoud; # invokes &LoudDecl::RealLoud
464 my @metal : RealLoud; # error: unknown attribute
465 my %metal : RealLoud; # error: unknown attribute
466 sub metal : RealLoud {...} # error: unknown attribute
467
468You can, of course, declare separate handlers for these types as well
469(but you'll need to specify C<no warnings 'redefine'> to do it quietly):
470
471 package LoudDecl;
472 use Attribute::Handlers;
473 no warnings 'redefine';
474
475 sub RealLoud :ATTR(SCALAR) { print "Yeeeeow!" }
476 sub RealLoud :ATTR(ARRAY) { print "Urrrrrrrrrr!" }
477 sub RealLoud :ATTR(HASH) { print "Arrrrrgggghhhhhh!" }
478 sub RealLoud :ATTR(CODE) { croak "Real loud sub torpedoed" }
479
480You can also explicitly indicate that a single handler is meant to be
481used for all types of referents like so:
482
483 package LoudDecl;
484 use Attribute::Handlers;
485
486 sub SeriousLoud :ATTR(ANY) { warn "Hearing loss imminent" }
487
488(I.e. C<ATTR(ANY)> is a synonym for C<:ATTR>).
489
490
491=head2 Non-interpretive attribute handlers
492
493Occasionally the strenuous efforts Attribute::Handlers makes to convert
494the data argument (C<$_[4]>) to a useable form before passing it to
495the handler get in the way.
496
497You can turn off that eagerness-to-help by declaring
498an attribute handler with the keyword C<RAWDATA>. For example:
499
500 sub Raw : ATTR(RAWDATA) {...}
501 sub Nekkid : ATTR(SCALAR,RAWDATA) {...}
502 sub Au::Naturale : ATTR(RAWDATA,ANY) {...}
503
504Then the handler makes absolutely no attempt to interpret the data it
505receives and simply passes it as a string:
506
507 my $power : Raw(1..100); # handlers receives "1..100"
508
509=head2 Phase-specific attribute handlers
510
511By default, attribute handlers are called at the end of the compilation
512phase (in a C<CHECK> block). This seems to be optimal in most cases because
513most things that can be defined are defined by that point but nothing has
514been executed.
515
516However, it is possible to set up attribute handlers that are called at
517other points in the program's compilation or execution, by explicitly
518stating the phase (or phases) in which you wish the attribute handler to
519be called. For example:
520
521 sub Early :ATTR(SCALAR,BEGIN) {...}
522 sub Normal :ATTR(SCALAR,CHECK) {...}
523 sub Late :ATTR(SCALAR,INIT) {...}
524 sub Final :ATTR(SCALAR,END) {...}
525 sub Bookends :ATTR(SCALAR,BEGIN,END) {...}
526
527As the last example indicates, a handler may be set up to be (re)called in
528two or more phases. The phase name is passed as the handler's final argument.
529
530Note that attribute handlers that are scheduled for the C<BEGIN> phase
531are handled as soon as the attribute is detected (i.e. before any
532subsequently defined C<BEGIN> blocks are executed).
533
534
535=head2 Attributes as C<tie> interfaces
536
537Attributes make an excellent and intuitive interface through which to tie
538variables. For example:
539
540 use Attribute::Handlers;
541 use Tie::Cycle;
542
543 sub UNIVERSAL::Cycle : ATTR(SCALAR) {
544 my ($package, $symbol, $referent, $attr, $data, $phase) = @_;
545 $data = [ $data ] unless ref $data eq 'ARRAY';
546 tie $$referent, 'Tie::Cycle', $data;
547 }
548
549 # and thereafter...
550
551 package main;
552
553 my $next : Cycle('A'..'Z'); # $next is now a tied variable
554
555 while (<>) {
556 print $next;
557 }
558
559Note that, because the C<Cycle> attribute receives its arguments in the
560C<$data> variable, if the attribute is given a list of arguments, C<$data>
561will consist of a single array reference; otherwise, it will consist of the
562single argument directly. Since Tie::Cycle requires its cycling values to
563be passed as an array reference, this means that we need to wrap
564non-array-reference arguments in an array constructor:
565
566 $data = [ $data ] unless ref $data eq 'ARRAY';
567
568Typically, however, things are the other way around: the tieable class expects
569its arguments as a flattened list, so the attribute looks like:
570
571 sub UNIVERSAL::Cycle : ATTR(SCALAR) {
572 my ($package, $symbol, $referent, $attr, $data, $phase) = @_;
573 my @data = ref $data eq 'ARRAY' ? @$data : $data;
574 tie $$referent, 'Tie::Whatever', @data;
575 }
576
577
578This software pattern is so widely applicable that Attribute::Handlers
579provides a way to automate it: specifying C<'autotie'> in the
580C<use Attribute::Handlers> statement. So, the cycling example,
581could also be written:
582
583 use Attribute::Handlers autotie => { Cycle => 'Tie::Cycle' };
584
585 # and thereafter...
586
587 package main;
588
589 my $next : Cycle(['A'..'Z']); # $next is now a tied variable
590
591 while (<>) {
592 print $next;
593
594Note that we now have to pass the cycling values as an array reference,
595since the C<autotie> mechanism passes C<tie> a list of arguments as a list
596(as in the Tie::Whatever example), I<not> as an array reference (as in
597the original Tie::Cycle example at the start of this section).
598
599The argument after C<'autotie'> is a reference to a hash in which each key is
600the name of an attribute to be created, and each value is the class to which
601variables ascribed that attribute should be tied.
602
603Note that there is no longer any need to import the Tie::Cycle module --
604Attribute::Handlers takes care of that automagically. You can even pass
605arguments to the module's C<import> subroutine, by appending them to the
606class name. For example:
607
608 use Attribute::Handlers
609 autotie => { Dir => 'Tie::Dir qw(DIR_UNLINK)' };
610
611If the attribute name is unqualified, the attribute is installed in the
612current package. Otherwise it is installed in the qualifier's package:
613
614 package Here;
615
616 use Attribute::Handlers autotie => {
617 Other::Good => Tie::SecureHash, # tie attr installed in Other::
618 Bad => Tie::Taxes, # tie attr installed in Here::
619 UNIVERSAL::Ugly => Software::Patent # tie attr installed everywhere
620 };
621
622Autoties are most commonly used in the module to which they actually tie,
623and need to export their attributes to any module that calls them. To
3c4b39be 624facilitate this, Attribute::Handlers recognizes a special "pseudo-class" --
0e9b9e0c 625C<__CALLER__>, which may be specified as the qualifier of an attribute:
626
627 package Tie::Me::Kangaroo:Down::Sport;
628
f903cfef 629 use Attribute::Handlers autotie => { '__CALLER__::Roo' => __PACKAGE__ };
0e9b9e0c 630
631This causes Attribute::Handlers to define the C<Roo> attribute in the package
632that imports the Tie::Me::Kangaroo:Down::Sport module.
633
f903cfef 634Note that it is important to quote the __CALLER__::Roo identifier because
635a bug in perl 5.8 will refuse to parse it and cause an unknown error.
636
0e9b9e0c 637=head3 Passing the tied object to C<tie>
638
639Occasionally it is important to pass a reference to the object being tied
640to the TIESCALAR, TIEHASH, etc. that ties it.
641
642The C<autotie> mechanism supports this too. The following code:
643
644 use Attribute::Handlers autotieref => { Selfish => Tie::Selfish };
645 my $var : Selfish(@args);
646
647has the same effect as:
648
649 tie my $var, 'Tie::Selfish', @args;
650
651But when C<"autotieref"> is used instead of C<"autotie">:
652
653 use Attribute::Handlers autotieref => { Selfish => Tie::Selfish };
654 my $var : Selfish(@args);
655
656the effect is to pass the C<tie> call an extra reference to the variable
657being tied:
658
659 tie my $var, 'Tie::Selfish', \$var, @args;
660
661
662
663=head1 EXAMPLES
664
665If the class shown in L<SYNOPSIS> were placed in the MyClass.pm
666module, then the following code:
667
668 package main;
669 use MyClass;
670
671 my MyClass $slr :Good :Bad(1**1-1) :Omni(-vorous);
672
673 package SomeOtherClass;
674 use base MyClass;
675
676 sub tent { 'acle' }
677
678 sub fn :Ugly(sister) :Omni('po',tent()) {...}
679 my @arr :Good :Omni(s/cie/nt/);
680 my %hsh :Good(q/bye) :Omni(q/bus/);
681
682
683would cause the following handlers to be invoked:
684
685 # my MyClass $slr :Good :Bad(1**1-1) :Omni(-vorous);
686
687 MyClass::Good:ATTR(SCALAR)( 'MyClass', # class
688 'LEXICAL', # no typeglob
689 \$slr, # referent
690 'Good', # attr name
691 undef # no attr data
692 'CHECK', # compiler phase
693 );
694
695 MyClass::Bad:ATTR(SCALAR)( 'MyClass', # class
696 'LEXICAL', # no typeglob
697 \$slr, # referent
698 'Bad', # attr name
699 0 # eval'd attr data
700 'CHECK', # compiler phase
701 );
702
703 MyClass::Omni:ATTR(SCALAR)( 'MyClass', # class
704 'LEXICAL', # no typeglob
705 \$slr, # referent
706 'Omni', # attr name
707 '-vorous' # eval'd attr data
708 'CHECK', # compiler phase
709 );
710
711
712 # sub fn :Ugly(sister) :Omni('po',tent()) {...}
713
714 MyClass::UGLY:ATTR(CODE)( 'SomeOtherClass', # class
715 \*SomeOtherClass::fn, # typeglob
716 \&SomeOtherClass::fn, # referent
717 'Ugly', # attr name
718 'sister' # eval'd attr data
719 'CHECK', # compiler phase
720 );
721
722 MyClass::Omni:ATTR(CODE)( 'SomeOtherClass', # class
723 \*SomeOtherClass::fn, # typeglob
724 \&SomeOtherClass::fn, # referent
725 'Omni', # attr name
726 ['po','acle'] # eval'd attr data
727 'CHECK', # compiler phase
728 );
729
730
731 # my @arr :Good :Omni(s/cie/nt/);
732
733 MyClass::Good:ATTR(ARRAY)( 'SomeOtherClass', # class
734 'LEXICAL', # no typeglob
735 \@arr, # referent
736 'Good', # attr name
737 undef # no attr data
738 'CHECK', # compiler phase
739 );
740
741 MyClass::Omni:ATTR(ARRAY)( 'SomeOtherClass', # class
742 'LEXICAL', # no typeglob
743 \@arr, # referent
744 'Omni', # attr name
745 "" # eval'd attr data
746 'CHECK', # compiler phase
747 );
748
749
750 # my %hsh :Good(q/bye) :Omni(q/bus/);
751
752 MyClass::Good:ATTR(HASH)( 'SomeOtherClass', # class
753 'LEXICAL', # no typeglob
754 \%hsh, # referent
755 'Good', # attr name
756 'q/bye' # raw attr data
757 'CHECK', # compiler phase
758 );
759
760 MyClass::Omni:ATTR(HASH)( 'SomeOtherClass', # class
761 'LEXICAL', # no typeglob
762 \%hsh, # referent
763 'Omni', # attr name
764 'bus' # eval'd attr data
765 'CHECK', # compiler phase
766 );
767
768
769Installing handlers into UNIVERSAL, makes them...err..universal.
770For example:
771
772 package Descriptions;
773 use Attribute::Handlers;
774
775 my %name;
776 sub name { return $name{$_[2]}||*{$_[1]}{NAME} }
777
778 sub UNIVERSAL::Name :ATTR {
779 $name{$_[2]} = $_[4];
780 }
781
782 sub UNIVERSAL::Purpose :ATTR {
783 print STDERR "Purpose of ", &name, " is $_[4]\n";
784 }
785
786 sub UNIVERSAL::Unit :ATTR {
787 print STDERR &name, " measured in $_[4]\n";
788 }
789
790Let's you write:
791
792 use Descriptions;
793
794 my $capacity : Name(capacity)
795 : Purpose(to store max storage capacity for files)
796 : Unit(Gb);
797
798
799 package Other;
800
801 sub foo : Purpose(to foo all data before barring it) { }
802
803 # etc.
804
805
806=head1 DIAGNOSTICS
807
808=over
809
810=item C<Bad attribute type: ATTR(%s)>
811
812An attribute handler was specified with an C<:ATTR(I<ref_type>)>, but the
813type of referent it was defined to handle wasn't one of the five permitted:
814C<SCALAR>, C<ARRAY>, C<HASH>, C<CODE>, or C<ANY>.
815
816=item C<Attribute handler %s doesn't handle %s attributes>
817
818A handler for attributes of the specified name I<was> defined, but not
819for the specified type of declaration. Typically encountered whe trying
820to apply a C<VAR> attribute handler to a subroutine, or a C<SCALAR>
821attribute handler to some other type of variable.
822
823=item C<Declaration of %s attribute in package %s may clash with future reserved word>
824
825A handler for an attributes with an all-lowercase name was declared. An
826attribute with an all-lowercase name might have a meaning to Perl
827itself some day, even though most don't yet. Use a mixed-case attribute
828name, instead.
829
830=item C<Can't have two ATTR specifiers on one subroutine>
831
832You just can't, okay?
833Instead, put all the specifications together with commas between them
834in a single C<ATTR(I<specification>)>.
835
836=item C<Can't autotie a %s>
837
838You can only declare autoties for types C<"SCALAR">, C<"ARRAY">, and
839C<"HASH">. They're the only things (apart from typeglobs -- which are
840not declarable) that Perl can tie.
841
842=item C<Internal error: %s symbol went missing>
843
844Something is rotten in the state of the program. An attributed
845subroutine ceased to exist between the point it was declared and the point
846at which its attribute handler(s) would have been called.
847
24952a9c 848=item C<Won't be able to apply END handler>
849
850You have defined an END handler for an attribute that is being applied
851to a lexical variable. Since the variable may not be available during END
852this won't happen.
853
0e9b9e0c 854=back
855
856=head1 AUTHOR
857
858Damian Conway (damian@conway.org)
859
860=head1 BUGS
861
862There are undoubtedly serious bugs lurking somewhere in code this funky :-)
863Bug reports and other feedback are most welcome.
864
865=head1 COPYRIGHT
866
867 Copyright (c) 2001, Damian Conway. All Rights Reserved.
868 This module is free software. It may be used, redistributed
869 and/or modified under the same terms as Perl itself.