This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
Documentation typo fix for Attribute::Handlers.
[perl5.git] / lib / Attribute / Handlers.pm
index dbd1bf4..ab5dafc 100644 (file)
@@ -2,7 +2,9 @@ package Attribute::Handlers;
 use 5.006;
 use Carp;
 use warnings;
-$VERSION = '0.75';
+use strict;
+use vars qw($VERSION $AUTOLOAD);
+$VERSION = '0.79';
 # $DB::single=1;
 
 my %symcache;
@@ -11,7 +13,10 @@ sub findsym {
        return $symcache{$pkg,$ref} if $symcache{$pkg,$ref};
        $type ||= ref($ref);
        my $found;
+       no strict 'refs';
         foreach my $sym ( values %{$pkg."::"} ) {
+           use strict;
+           next unless ref ( \$sym ) eq 'GLOB';
             return $symcache{$pkg,$ref} = \$sym
                if *{$sym}{$type} && *{$sym}{$type} == $ref;
        }
@@ -31,6 +36,14 @@ my @declarations;
 my %raw;
 my %phase;
 my %sigil = (SCALAR=>'$', ARRAY=>'@', HASH=>'%');
+my $global_phase = 0;
+my %global_phases = (
+       BEGIN   => 0,
+       CHECK   => 1,
+       INIT    => 2,
+       END     => 3,
+);
+my @global_phases = qw(BEGIN CHECK INIT END);
 
 sub _usage_AH_ {
        croak "Usage: use $_[0] autotie => {AttrName => TieClassName,...}";
@@ -44,8 +57,7 @@ sub import {
     while (@_) {
        my $cmd = shift;
         if ($cmd =~ /^autotie((?:ref)?)$/) {
-           my $tiedata = '($was_arrayref ? $data : @$data)';
-              $tiedata = ($1 ? '$ref, ' : '') . $tiedata;
+           my $tiedata = ($1 ? '$ref, ' : '') . '@$data';
             my $mapping = shift;
            _usage_AH_ $class unless ref($mapping) eq 'HASH';
            while (my($attr, $tieclass) = each %$mapping) {
@@ -53,7 +65,7 @@ sub import {
                my $args = $3||'()';
                _usage_AH_ $class unless $attr =~ $qual_id
                                 && $tieclass =~ $qual_id
-                                && eval "use base $tieclass; 1";
+                                && eval "use base q\0$tieclass\0; 1";
                if ($tieclass->isa('Exporter')) {
                    local $Exporter::ExportLevel = 2;
                    $tieclass->import(eval $args);
@@ -87,29 +99,31 @@ sub _resolve_lastattr {
        warn "Declaration of $name attribute in package $lastattr{pkg} may clash with future reserved word\n"
                if $^W and $name !~ /[A-Z]/;
        foreach ( @{$validtype{$lastattr{type}}} ) {
+               no strict 'refs';
                *{"$lastattr{pkg}::_ATTR_${_}_${name}"} = $lastattr{ref};
        }
        %lastattr = ();
 }
 
 sub AUTOLOAD {
+       return if $AUTOLOAD =~ /::DESTROY$/;
        my ($class) = $AUTOLOAD =~ m/(.*)::/g;
        $AUTOLOAD =~ m/_ATTR_(.*?)_(.*)/ or
            croak "Can't locate class method '$AUTOLOAD' via package '$class'";
-       croak "Attribute handler '$3' doesn't handle $2 attributes";
+       croak "Attribute handler '$2' doesn't handle $1 attributes";
 }
 
-sub DESTROY {}
-
-my $builtin = qr/lvalue|method|locked/;
+my $builtin = qr/lvalue|method|locked|unique|shared/;
 
 sub _gen_handler_AH_() {
        return sub {
            _resolve_lastattr;
            my ($pkg, $ref, @attrs) = @_;
+           my (undef, $filename, $linenum) = caller 2;
            foreach (@attrs) {
                my ($attr, $data) = /^([a-z_]\w*)(?:[(](.*)[)])?$/is or next;
                if ($attr eq 'ATTR') {
+                       no strict 'refs';
                        $data ||= "ANY";
                        $raw{$ref} = $data =~ s/\s*,?\s*RAWDATA\s*,?\s*//;
                        $phase{$ref}{BEGIN} = 1
@@ -121,6 +135,8 @@ sub _gen_handler_AH_() {
                        $phase{$ref}{CHECK} = 1
                                if $data =~ s/\s*,?\s*(CHECK)\s*,?\s*//
                                || ! keys %{$phase{$ref}};
+                       # Added for cleanup to not pollute next call.
+                       (%lastattr = ()),
                        croak "Can't have two ATTR specifiers on one subroutine"
                                if keys %lastattr;
                        croak "Bad attribute type: ATTR($data)"
@@ -128,12 +144,27 @@ sub _gen_handler_AH_() {
                        %lastattr=(pkg=>$pkg,ref=>$ref,type=>$data);
                }
                else {
-                       my $handler = $pkg->can($attr);
+                       my $type = ref $ref;
+                       my $handler = $pkg->can("_ATTR_${type}_${attr}");
                        next unless $handler;
                        my $decl = [$pkg, $ref, $attr, $data,
-                                   $raw{$handler}, $phase{$handler}];
-                       _apply_handler_AH_($decl,'BEGIN');
-                       push @declarations, $decl;
+                                   $raw{$handler}, $phase{$handler}, $filename, $linenum];
+                       foreach my $gphase (@global_phases) {
+                           _apply_handler_AH_($decl,$gphase)
+                               if $global_phases{$gphase} <= $global_phase;
+                       }
+                       if ($global_phase != 0) {
+                               # if _gen_handler_AH_ is being called after 
+                               # CHECK it's for a lexical, so make sure
+                               # it didn't want to run anything later
+                       
+                               local $Carp::CarpLevel = 2;
+                               carp "Won't be able to apply END handler"
+                                       if $phase{$handler}{END};
+                       }
+                       else {
+                               push @declarations, $decl
+                       }
                }
                $_ = undef;
            }
@@ -141,13 +172,17 @@ sub _gen_handler_AH_() {
        }
 }
 
-*{"MODIFY_${_}_ATTRIBUTES"} = _gen_handler_AH_ foreach @{$validtype{ANY}};
-push @UNIVERSAL::ISA, 'Attribute::Handlers'
-       unless grep /^Attribute::Handlers$/, @UNIVERSAL::ISA;
+{
+    no strict 'refs';
+    *{"Attribute::Handlers::UNIVERSAL::MODIFY_${_}_ATTRIBUTES"} =
+       _gen_handler_AH_ foreach @{$validtype{ANY}};
+}
+push @UNIVERSAL::ISA, 'Attribute::Handlers::UNIVERSAL'
+       unless grep /^Attribute::Handlers::UNIVERSAL$/, @UNIVERSAL::ISA;
 
 sub _apply_handler_AH_ {
        my ($declaration, $phase) = @_;
-       my ($pkg, $ref, $attr, $data, $raw, $handlerphase) = @$declaration;
+       my ($pkg, $ref, $attr, $data, $raw, $handlerphase, $filename, $linenum) = @$declaration;
        return unless $handlerphase->{$phase};
        # print STDERR "Handling $attr on $ref in $phase with [$data]\n";
        my $type = ref $ref;
@@ -155,28 +190,40 @@ sub _apply_handler_AH_ {
        my $sym = findsym($pkg, $ref);
        $sym ||= $type eq 'CODE' ? 'ANON' : 'LEXICAL';
        no warnings;
-       my $evaled = !$raw && eval("package $pkg; no warnings;
-                                   local \$SIG{__WARN__}=sub{die}; [$data]");
-       $data = ($evaled && $data =~ /^\s*\[/)  ? [$evaled]
-             : ($evaled)                       ? $evaled
-             :                                   [$data];
+       if (!$raw && defined($data)) {
+           if ($data ne '') {
+               my $evaled = eval("package $pkg; no warnings; no strict;
+                                  local \$SIG{__WARN__}=sub{die}; [$data]");
+               $data = $evaled unless $@;
+           }
+           else { $data = undef }
+       }
        $pkg->$handler($sym,
                       (ref $sym eq 'GLOB' ? *{$sym}{ref $ref}||$ref : $ref),
                       $attr,
-                      (@$data>1? $data : $data->[0]),
+                      $data,
                       $phase,
+                      $filename,
+                      $linenum,
                      );
        return 1;
 }
 
-CHECK {
-       _resolve_lastattr;
-       _apply_handler_AH_($_,'CHECK') foreach @declarations;
-}
+{
+        no warnings 'void';
+        CHECK {
+               $global_phase++;
+               _resolve_lastattr;
+               _apply_handler_AH_($_,'CHECK') foreach @declarations;
+        }
 
-INIT { _apply_handler_AH_($_,'INIT') foreach @declarations }
+        INIT {
+                $global_phase++;
+                _apply_handler_AH_($_,'INIT') foreach @declarations
+        }
+}
 
-END { _apply_handler_AH_($_,'END') foreach @declarations }
+END { $global_phase++; _apply_handler_AH_($_,'END') foreach @declarations }
 
 1;
 __END__
@@ -187,8 +234,8 @@ Attribute::Handlers - Simpler definition of attribute handlers
 
 =head1 VERSION
 
-This document describes version 0.75 of Attribute::Handlers,
-released September  3, 2001.
+This document describes version 0.79 of Attribute::Handlers,
+released November 25, 2007.
 
 =head1 SYNOPSIS
 
@@ -259,27 +306,29 @@ and subroutines subsequently defined in that package, or in packages
 derived from that package may be given attributes with the same names as
 the attribute handler subroutines, which will then be called in one of
 the compilation phases (i.e. in a C<BEGIN>, C<CHECK>, C<INIT>, or C<END>
-block).
+block). (C<UNITCHECK> blocks don't correspond to a global compilation
+phase, so they can't be specified here.)
 
 To create a handler, define it as a subroutine with the same name as
 the desired attribute, and declare the subroutine itself with the  
 attribute C<:ATTR>. For example:
 
-       package LoudDecl;
-       use Attribute::Handlers;
-
-       sub Loud :ATTR {
-               my ($package, $symbol, $referent, $attr, $data, $phase) = @_;
-               print STDERR
-                       ref($referent), " ",
-                       *{$symbol}{NAME}, " ",
-                       "($referent) ", "was just declared ",
-                       "and ascribed the ${attr} attribute ",
-                       "with data ($data)\n",
-                       "in phase $phase\n";
-       }
+    package LoudDecl;
+    use Attribute::Handlers;
+
+    sub Loud :ATTR {
+       my ($package, $symbol, $referent, $attr, $data, $phase, $filename, $linenum) = @_;
+       print STDERR
+           ref($referent), " ",
+           *{$symbol}{NAME}, " ",
+           "($referent) ", "was just declared ",
+           "and ascribed the ${attr} attribute ",
+           "with data ($data)\n",
+           "in phase $phase\n",
+           "in file $filename at line $linenum\n";
+    }
 
-This creates an handler for the attribute C<:Loud> in the class LoudDecl.
+This creates a handler for the attribute C<:Loud> in the class LoudDecl.
 Thereafter, any subroutine declared with a C<:Loud> attribute in the class
 LoudDecl:
 
@@ -313,7 +362,15 @@ any data associated with that attribute;
 
 =item [5]
 
-the name of the phase in which the handler is being invoked.
+the name of the phase in which the handler is being invoked;
+
+=item [6]
+
+the filename in which the handler is being invoked;
+
+=item [7]
+
+the line number in this file.
 
 =back
 
@@ -338,40 +395,46 @@ which it belongs, so the symbol table argument (C<$_[1]>) is set to the
 string C<'LEXICAL'> in that case. Likewise, ascribing an attribute to
 an anonymous subroutine results in a symbol table argument of C<'ANON'>.
 
-The data argument passes in the value (if any) associated with the 
+The data argument passes in the value (if any) associated with the
 attribute. For example, if C<&foo> had been declared:
 
         sub foo :Loud("turn it up to 11, man!") {...}
 
-then the string C<"turn it up to 11, man!"> would be passed as the
-last argument.
+then a reference to an array containing the string
+C<"turn it up to 11, man!"> would be passed as the last argument.
 
 Attribute::Handlers makes strenuous efforts to convert
 the data argument (C<$_[4]>) to a useable form before passing it to
 the handler (but see L<"Non-interpretive attribute handlers">).
+If those efforts succeed, the interpreted data is passed in an array
+reference; if they fail, the raw data is passed as a string.
 For example, all of these:
 
-        sub foo :Loud(till=>ears=>are=>bleeding) {...}
-        sub foo :Loud(['till','ears','are','bleeding']) {...}
-        sub foo :Loud(qw/till ears are bleeding/) {...}
-        sub foo :Loud(qw/my, ears, are, bleeding/) {...}
-        sub foo :Loud(till,ears,are,bleeding) {...}
+    sub foo :Loud(till=>ears=>are=>bleeding) {...}
+    sub foo :Loud(qw/till ears are bleeding/) {...}
+    sub foo :Loud(qw/my, ears, are, bleeding/) {...}
+    sub foo :Loud(till,ears,are,bleeding) {...}
 
 causes it to pass C<['till','ears','are','bleeding']> as the handler's
-data argument. However, if the data can't be parsed as valid Perl, then
-it is passed as an uninterpreted string. For example:
+data argument. While:
+
+    sub foo :Loud(['till','ears','are','bleeding']) {...}
 
-        sub foo :Loud(my,ears,are,bleeding) {...}
-        sub foo :Loud(qw/my ears are bleeding) {...}
+causes it to pass C<[ ['till','ears','are','bleeding'] ]>; the array
+reference specified in the data being passed inside the standard
+array reference indicating successful interpretation.
 
-cause the strings C<'my,ears,are,bleeding'> and C<'qw/my ears are bleeding'>
-respectively to be passed as the data argument.
+However, if the data can't be parsed as valid Perl, then
+it is passed as an uninterpreted string. For example:
 
-If the attribute has only a single associated scalar data value, that value is
-passed as a scalar. If multiple values are associated, they are passed as an
-array reference. If no value is associated with the attribute, C<undef> is
-passed.
+    sub foo :Loud(my,ears,are,bleeding) {...}
+    sub foo :Loud(qw/my ears are bleeding) {...}
 
+cause the strings C<'my,ears,are,bleeding'> and
+C<'qw/my ears are bleeding'> respectively to be passed as the
+data argument.
+
+If no value is associated with the attribute, C<undef> is passed.
 
 =head2 Typed lexicals
 
@@ -441,7 +504,7 @@ the data argument (C<$_[4]>) to a useable form before passing it to
 the handler get in the way.
 
 You can turn off that eagerness-to-help by declaring
-an attribute handler with the the keyword C<RAWDATA>. For example:
+an attribute handler with the keyword C<RAWDATA>. For example:
 
         sub Raw          : ATTR(RAWDATA) {...}
         sub Nekkid       : ATTR(SCALAR,RAWDATA) {...}
@@ -502,9 +565,28 @@ variables. For example:
                 print $next;
         }
 
-In fact, this pattern is so widely applicable that Attribute::Handlers
+Note that, because the C<Cycle> attribute receives its arguments in the
+C<$data> variable, if the attribute is given a list of arguments, C<$data>
+will consist of a single array reference; otherwise, it will consist of the
+single argument directly. Since Tie::Cycle requires its cycling values to
+be passed as an array reference, this means that we need to wrap
+non-array-reference arguments in an array constructor:
+
+        $data = [ $data ] unless ref $data eq 'ARRAY';
+
+Typically, however, things are the other way around: the tieable class expects
+its arguments as a flattened list, so the attribute looks like:
+
+        sub UNIVERSAL::Cycle : ATTR(SCALAR) {
+                my ($package, $symbol, $referent, $attr, $data, $phase) = @_;
+                my @data = ref $data eq 'ARRAY' ? @$data : $data;
+                tie $$referent, 'Tie::Whatever', @data;
+        }
+
+
+This software pattern is so widely applicable that Attribute::Handlers
 provides a way to automate it: specifying C<'autotie'> in the
-C<use Attribute::Handlers> statement. So, the previous example,
+C<use Attribute::Handlers> statement. So, the cycling example,
 could also be written:
 
         use Attribute::Handlers autotie => { Cycle => 'Tie::Cycle' };
@@ -513,11 +595,16 @@ could also be written:
 
         package main;
 
-        my $next : Cycle('A'..'Z');     # $next is now a tied variable
+        my $next : Cycle(['A'..'Z']);     # $next is now a tied variable
 
         while (<>) {
                 print $next;
 
+Note that we now have to pass the cycling values as an array reference,
+since the C<autotie> mechanism passes C<tie> a list of arguments as a list
+(as in the Tie::Whatever example), I<not> as an array reference (as in
+the original Tie::Cycle example at the start of this section).
+
 The argument after C<'autotie'> is a reference to a hash in which each key is
 the name of an attribute to be created, and each value is the class to which
 variables ascribed that attribute should be tied.
@@ -543,16 +630,19 @@ current package. Otherwise it is installed in the qualifier's package:
 
 Autoties are most commonly used in the module to which they actually tie, 
 and need to export their attributes to any module that calls them. To
-facilitiate this, Attribute::Handlers recognizes a special "pseudo-class" --
+facilitate this, Attribute::Handlers recognizes a special "pseudo-class" --
 C<__CALLER__>, which may be specified as the qualifier of an attribute:
 
         package Tie::Me::Kangaroo:Down::Sport;
 
-        use Attribute::Handlers autotie => { __CALLER__::Roo => __PACKAGE__ };
+        use Attribute::Handlers autotie => { '__CALLER__::Roo' => __PACKAGE__ };
 
 This causes Attribute::Handlers to define the C<Roo> attribute in the package
 that imports the Tie::Me::Kangaroo:Down::Sport module.
 
+Note that it is important to quote the __CALLER__::Roo identifier because
+a bug in perl 5.8 will refuse to parse it and cause an unknown error.
+
 =head3 Passing the tied object to C<tie>
 
 Occasionally it is important to pass a reference to the object being tied
@@ -596,7 +686,7 @@ module, then the following code:
 
         sub fn :Ugly(sister) :Omni('po',tent()) {...}
         my @arr :Good :Omni(s/cie/nt/);
-        my %hsh :Good(q/bye) :Omni(q/bus/);
+        my %hsh :Good(q/bye/) :Omni(q/bus/);
 
 
 would cause the following handlers to be invoked:
@@ -755,7 +845,7 @@ in a single C<ATTR(I<specification>)>.
 =item C<Can't autotie a %s>
 
 You can only declare autoties for types C<"SCALAR">, C<"ARRAY">, and
-C<"SCALAR">. They're the only things (apart from typeglobs -- which are
+C<"HASH">. They're the only things (apart from typeglobs -- which are
 not declarable) that Perl can tie.
 
 =item C<Internal error: %s symbol went missing>
@@ -764,6 +854,12 @@ Something is rotten in the state of the program. An attributed
 subroutine ceased to exist between the point it was declared and the point
 at which its attribute handler(s) would have been called.
 
+=item C<Won't be able to apply END handler>
+
+You have defined an END handler for an attribute that is being applied
+to a lexical variable.  Since the variable may not be available during END
+this won't happen.
+
 =back
 
 =head1 AUTHOR