Perl 5 version 22.4 documentation

Attribute::Handlers

NAME

Attribute::Handlers - Simpler definition of attribute handlers

VERSION

This document describes version 0.97 of Attribute::Handlers.

SYNOPSIS

  1. package MyClass;
  2. require 5.006;
  3. use Attribute::Handlers;
  4. no warnings 'redefine';
  5. sub Good : ATTR(SCALAR) {
  6. my ($package, $symbol, $referent, $attr, $data) = @_;
  7. # Invoked for any scalar variable with a :Good attribute,
  8. # provided the variable was declared in MyClass (or
  9. # a derived class) or typed to MyClass.
  10. # Do whatever to $referent here (executed in CHECK phase).
  11. ...
  12. }
  13. sub Bad : ATTR(SCALAR) {
  14. # Invoked for any scalar variable with a :Bad attribute,
  15. # provided the variable was declared in MyClass (or
  16. # a derived class) or typed to MyClass.
  17. ...
  18. }
  19. sub Good : ATTR(ARRAY) {
  20. # Invoked for any array variable with a :Good attribute,
  21. # provided the variable was declared in MyClass (or
  22. # a derived class) or typed to MyClass.
  23. ...
  24. }
  25. sub Good : ATTR(HASH) {
  26. # Invoked for any hash variable with a :Good attribute,
  27. # provided the variable was declared in MyClass (or
  28. # a derived class) or typed to MyClass.
  29. ...
  30. }
  31. sub Ugly : ATTR(CODE) {
  32. # Invoked for any subroutine declared in MyClass (or a
  33. # derived class) with an :Ugly attribute.
  34. ...
  35. }
  36. sub Omni : ATTR {
  37. # Invoked for any scalar, array, hash, or subroutine
  38. # with an :Omni attribute, provided the variable or
  39. # subroutine was declared in MyClass (or a derived class)
  40. # or the variable was typed to MyClass.
  41. # Use ref($_[2]) to determine what kind of referent it was.
  42. ...
  43. }
  44. use Attribute::Handlers autotie => { Cycle => Tie::Cycle };
  45. my $next : Cycle(['A'..'Z']);

DESCRIPTION

This module, when inherited by a package, allows that package's class to define attribute handler subroutines for specific attributes. Variables 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 BEGIN, CHECK, INIT, or END block). (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 :ATTR . For example:

  1. package LoudDecl;
  2. use Attribute::Handlers;
  3. sub Loud :ATTR {
  4. my ($package, $symbol, $referent, $attr, $data, $phase,
  5. $filename, $linenum) = @_;
  6. print STDERR
  7. ref($referent), " ",
  8. *{$symbol}{NAME}, " ",
  9. "($referent) ", "was just declared ",
  10. "and ascribed the ${attr} attribute ",
  11. "with data ($data)\n",
  12. "in phase $phase\n",
  13. "in file $filename at line $linenum\n";
  14. }

This creates a handler for the attribute :Loud in the class LoudDecl. Thereafter, any subroutine declared with a :Loud attribute in the class LoudDecl:

  1. package LoudDecl;
  2. sub foo: Loud {...}

causes the above handler to be invoked, and passed:

  • [0]

    the name of the package into which it was declared;

  • [1]

    a reference to the symbol table entry (typeglob) containing the subroutine;

  • [2]

    a reference to the subroutine;

  • [3]

    the name of the attribute;

  • [4]

    any data associated with that attribute;

  • [5]

    the name of the phase in which the handler is being invoked;

  • [6]

    the filename in which the handler is being invoked;

  • [7]

    the line number in this file.

Likewise, declaring any variables with the :Loud attribute within the package:

  1. package LoudDecl;
  2. my $foo :Loud;
  3. my @foo :Loud;
  4. my %foo :Loud;

will cause the handler to be called with a similar argument list (except, of course, that $_[2] will be a reference to the variable).

The package name argument will typically be the name of the class into which the subroutine was declared, but it may also be the name of a derived class (since handlers are inherited).

If a lexical variable is given an attribute, there is no symbol table to which it belongs, so the symbol table argument ($_[1] ) is set to the string 'LEXICAL' in that case. Likewise, ascribing an attribute to an anonymous subroutine results in a symbol table argument of 'ANON' .

The data argument passes in the value (if any) associated with the attribute. For example, if &foo had been declared:

  1. sub foo :Loud("turn it up to 11, man!") {...}

then a reference to an array containing the string "turn it up to 11, man!" would be passed as the last argument.

Attribute::Handlers makes strenuous efforts to convert the data argument ($_[4] ) to a usable form before passing it to the handler (but see 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:

  1. sub foo :Loud(till=>ears=>are=>bleeding) {...}
  2. sub foo :Loud(qw/till ears are bleeding/) {...}
  3. sub foo :Loud(qw/till, ears, are, bleeding/) {...}
  4. sub foo :Loud(till,ears,are,bleeding) {...}

causes it to pass ['till','ears','are','bleeding'] as the handler's data argument. While:

  1. sub foo :Loud(['till','ears','are','bleeding']) {...}

causes it to pass [ ['till','ears','are','bleeding'] ] ; the array reference specified in the data being passed inside the standard array reference indicating successful interpretation.

However, if the data can't be parsed as valid Perl, then it is passed as an uninterpreted string. For example:

  1. sub foo :Loud(my,ears,are,bleeding) {...}
  2. sub foo :Loud(qw/my ears are bleeding) {...}

cause the strings 'my,ears,are,bleeding' and 'qw/my ears are bleeding' respectively to be passed as the data argument.

If no value is associated with the attribute, undef is passed.

Typed lexicals

Regardless of the package in which it is declared, if a lexical variable is ascribed an attribute, the handler that is invoked is the one belonging to the package to which it is typed. For example, the following declarations:

  1. package OtherClass;
  2. my LoudDecl $loudobj : Loud;
  3. my LoudDecl @loudobjs : Loud;
  4. my LoudDecl %loudobjex : Loud;

causes the LoudDecl::Loud handler to be invoked (even if OtherClass also defines a handler for :Loud attributes).

Type-specific attribute handlers

If an attribute handler is declared and the :ATTR specifier is given the name of a built-in type (SCALAR , ARRAY , HASH , or CODE ), the handler is only applied to declarations of that type. For example, the following definition:

  1. package LoudDecl;
  2. sub RealLoud :ATTR(SCALAR) { print "Yeeeeow!" }

creates an attribute handler that applies only to scalars:

  1. package Painful;
  2. use base LoudDecl;
  3. my $metal : RealLoud; # invokes &LoudDecl::RealLoud
  4. my @metal : RealLoud; # error: unknown attribute
  5. my %metal : RealLoud; # error: unknown attribute
  6. sub metal : RealLoud {...} # error: unknown attribute

You can, of course, declare separate handlers for these types as well (but you'll need to specify no warnings 'redefine' to do it quietly):

  1. package LoudDecl;
  2. use Attribute::Handlers;
  3. no warnings 'redefine';
  4. sub RealLoud :ATTR(SCALAR) { print "Yeeeeow!" }
  5. sub RealLoud :ATTR(ARRAY) { print "Urrrrrrrrrr!" }
  6. sub RealLoud :ATTR(HASH) { print "Arrrrrgggghhhhhh!" }
  7. sub RealLoud :ATTR(CODE) { croak "Real loud sub torpedoed" }

You can also explicitly indicate that a single handler is meant to be used for all types of referents like so:

  1. package LoudDecl;
  2. use Attribute::Handlers;
  3. sub SeriousLoud :ATTR(ANY) { warn "Hearing loss imminent" }

(I.e. ATTR(ANY) is a synonym for :ATTR ).

Non-interpretive attribute handlers

Occasionally the strenuous efforts Attribute::Handlers makes to convert the data argument ($_[4] ) to a usable 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 keyword RAWDATA . For example:

  1. sub Raw : ATTR(RAWDATA) {...}
  2. sub Nekkid : ATTR(SCALAR,RAWDATA) {...}
  3. sub Au::Naturale : ATTR(RAWDATA,ANY) {...}

Then the handler makes absolutely no attempt to interpret the data it receives and simply passes it as a string:

  1. my $power : Raw(1..100); # handlers receives "1..100"

Phase-specific attribute handlers

By default, attribute handlers are called at the end of the compilation phase (in a CHECK block). This seems to be optimal in most cases because most things that can be defined are defined by that point but nothing has been executed.

However, it is possible to set up attribute handlers that are called at other points in the program's compilation or execution, by explicitly stating the phase (or phases) in which you wish the attribute handler to be called. For example:

  1. sub Early :ATTR(SCALAR,BEGIN) {...}
  2. sub Normal :ATTR(SCALAR,CHECK) {...}
  3. sub Late :ATTR(SCALAR,INIT) {...}
  4. sub Final :ATTR(SCALAR,END) {...}
  5. sub Bookends :ATTR(SCALAR,BEGIN,END) {...}

As the last example indicates, a handler may be set up to be (re)called in two or more phases. The phase name is passed as the handler's final argument.

Note that attribute handlers that are scheduled for the BEGIN phase are handled as soon as the attribute is detected (i.e. before any subsequently defined BEGIN blocks are executed).

Attributes as tie interfaces

Attributes make an excellent and intuitive interface through which to tie variables. For example:

  1. use Attribute::Handlers;
  2. use Tie::Cycle;
  3. sub UNIVERSAL::Cycle : ATTR(SCALAR) {
  4. my ($package, $symbol, $referent, $attr, $data, $phase) = @_;
  5. $data = [ $data ] unless ref $data eq 'ARRAY';
  6. tie $$referent, 'Tie::Cycle', $data;
  7. }
  8. # and thereafter...
  9. package main;
  10. my $next : Cycle('A'..'Z'); # $next is now a tied variable
  11. while (<>) {
  12. print $next;
  13. }

Note that, because the Cycle attribute receives its arguments in the $data variable, if the attribute is given a list of arguments, $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:

  1. $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:

  1. sub UNIVERSAL::Cycle : ATTR(SCALAR) {
  2. my ($package, $symbol, $referent, $attr, $data, $phase) = @_;
  3. my @data = ref $data eq 'ARRAY' ? @$data : $data;
  4. tie $$referent, 'Tie::Whatever', @data;
  5. }

This software pattern is so widely applicable that Attribute::Handlers provides a way to automate it: specifying 'autotie' in the use Attribute::Handlers statement. So, the cycling example, could also be written:

  1. use Attribute::Handlers autotie => { Cycle => 'Tie::Cycle' };
  2. # and thereafter...
  3. package main;
  4. my $next : Cycle(['A'..'Z']); # $next is now a tied variable
  5. while (<>) {
  6. print $next;
  7. }

Note that we now have to pass the cycling values as an array reference, since the autotie mechanism passes tie a list of arguments as a list (as in the Tie::Whatever example), not as an array reference (as in the original Tie::Cycle example at the start of this section).

The argument after '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.

Note that there is no longer any need to import the Tie::Cycle module -- Attribute::Handlers takes care of that automagically. You can even pass arguments to the module's import subroutine, by appending them to the class name. For example:

  1. use Attribute::Handlers
  2. autotie => { Dir => 'Tie::Dir qw(DIR_UNLINK)' };

If the attribute name is unqualified, the attribute is installed in the current package. Otherwise it is installed in the qualifier's package:

  1. package Here;
  2. use Attribute::Handlers autotie => {
  3. Other::Good => Tie::SecureHash, # tie attr installed in Other::
  4. Bad => Tie::Taxes, # tie attr installed in Here::
  5. UNIVERSAL::Ugly => Software::Patent # tie attr installed everywhere
  6. };

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 facilitate this, Attribute::Handlers recognizes a special "pseudo-class" -- __CALLER__ , which may be specified as the qualifier of an attribute:

  1. package Tie::Me::Kangaroo:Down::Sport;
  2. use Attribute::Handlers autotie =>
  3. { '__CALLER__::Roo' => __PACKAGE__ };

This causes Attribute::Handlers to define the 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.

Passing the tied object to tie

Occasionally it is important to pass a reference to the object being tied to the TIESCALAR, TIEHASH, etc. that ties it.

The autotie mechanism supports this too. The following code:

  1. use Attribute::Handlers autotieref => { Selfish => Tie::Selfish };
  2. my $var : Selfish(@args);

has the same effect as:

  1. tie my $var, 'Tie::Selfish', @args;

But when "autotieref" is used instead of "autotie" :

  1. use Attribute::Handlers autotieref => { Selfish => Tie::Selfish };
  2. my $var : Selfish(@args);

the effect is to pass the tie call an extra reference to the variable being tied:

  1. tie my $var, 'Tie::Selfish', \$var, @args;

EXAMPLES

If the class shown in SYNOPSIS were placed in the MyClass.pm module, then the following code:

  1. package main;
  2. use MyClass;
  3. my MyClass $slr :Good :Bad(1**1-1) :Omni(-vorous);
  4. package SomeOtherClass;
  5. use base MyClass;
  6. sub tent { 'acle' }
  7. sub fn :Ugly(sister) :Omni('po',tent()) {...}
  8. my @arr :Good :Omni(s/cie/nt/);
  9. my %hsh :Good(q/bye/) :Omni(q/bus/);

would cause the following handlers to be invoked:

  1. # my MyClass $slr :Good :Bad(1**1-1) :Omni(-vorous);
  2. MyClass::Good:ATTR(SCALAR)( 'MyClass', # class
  3. 'LEXICAL', # no typeglob
  4. \$slr, # referent
  5. 'Good', # attr name
  6. undef # no attr data
  7. 'CHECK', # compiler phase
  8. );
  9. MyClass::Bad:ATTR(SCALAR)( 'MyClass', # class
  10. 'LEXICAL', # no typeglob
  11. \$slr, # referent
  12. 'Bad', # attr name
  13. 0 # eval'd attr data
  14. 'CHECK', # compiler phase
  15. );
  16. MyClass::Omni:ATTR(SCALAR)( 'MyClass', # class
  17. 'LEXICAL', # no typeglob
  18. \$slr, # referent
  19. 'Omni', # attr name
  20. '-vorous' # eval'd attr data
  21. 'CHECK', # compiler phase
  22. );
  23. # sub fn :Ugly(sister) :Omni('po',tent()) {...}
  24. MyClass::UGLY:ATTR(CODE)( 'SomeOtherClass', # class
  25. \*SomeOtherClass::fn, # typeglob
  26. \&SomeOtherClass::fn, # referent
  27. 'Ugly', # attr name
  28. 'sister' # eval'd attr data
  29. 'CHECK', # compiler phase
  30. );
  31. MyClass::Omni:ATTR(CODE)( 'SomeOtherClass', # class
  32. \*SomeOtherClass::fn, # typeglob
  33. \&SomeOtherClass::fn, # referent
  34. 'Omni', # attr name
  35. ['po','acle'] # eval'd attr data
  36. 'CHECK', # compiler phase
  37. );
  38. # my @arr :Good :Omni(s/cie/nt/);
  39. MyClass::Good:ATTR(ARRAY)( 'SomeOtherClass', # class
  40. 'LEXICAL', # no typeglob
  41. \@arr, # referent
  42. 'Good', # attr name
  43. undef # no attr data
  44. 'CHECK', # compiler phase
  45. );
  46. MyClass::Omni:ATTR(ARRAY)( 'SomeOtherClass', # class
  47. 'LEXICAL', # no typeglob
  48. \@arr, # referent
  49. 'Omni', # attr name
  50. "" # eval'd attr data
  51. 'CHECK', # compiler phase
  52. );
  53. # my %hsh :Good(q/bye) :Omni(q/bus/);
  54. MyClass::Good:ATTR(HASH)( 'SomeOtherClass', # class
  55. 'LEXICAL', # no typeglob
  56. \%hsh, # referent
  57. 'Good', # attr name
  58. 'q/bye' # raw attr data
  59. 'CHECK', # compiler phase
  60. );
  61. MyClass::Omni:ATTR(HASH)( 'SomeOtherClass', # class
  62. 'LEXICAL', # no typeglob
  63. \%hsh, # referent
  64. 'Omni', # attr name
  65. 'bus' # eval'd attr data
  66. 'CHECK', # compiler phase
  67. );

Installing handlers into UNIVERSAL, makes them...err..universal. For example:

  1. package Descriptions;
  2. use Attribute::Handlers;
  3. my %name;
  4. sub name { return $name{$_[2]}||*{$_[1]}{NAME} }
  5. sub UNIVERSAL::Name :ATTR {
  6. $name{$_[2]} = $_[4];
  7. }
  8. sub UNIVERSAL::Purpose :ATTR {
  9. print STDERR "Purpose of ", &name, " is $_[4]\n";
  10. }
  11. sub UNIVERSAL::Unit :ATTR {
  12. print STDERR &name, " measured in $_[4]\n";
  13. }

Let's you write:

  1. use Descriptions;
  2. my $capacity : Name(capacity)
  3. : Purpose(to store max storage capacity for files)
  4. : Unit(Gb);
  5. package Other;
  6. sub foo : Purpose(to foo all data before barring it) { }
  7. # etc.

UTILITY FUNCTIONS

This module offers a single utility function, findsym() .

  • findsym
    1. my $symbol = Attribute::Handlers::findsym($package, $referent);

    The function looks in the symbol table of $package for the typeglob for $referent , which is a reference to a variable or subroutine (SCALAR, ARRAY, HASH, or CODE). If it finds the typeglob, it returns it. Otherwise, it returns undef. Note that findsym memoizes the typeglobs it has previously successfully found, so subsequent calls with the same arguments should be much faster.

DIAGNOSTICS

  • Bad attribute type: ATTR(%s)

    An attribute handler was specified with an :ATTR(ref_type), but the type of referent it was defined to handle wasn't one of the five permitted: SCALAR , ARRAY , HASH , CODE , or ANY .

  • Attribute handler %s doesn't handle %s attributes

    A handler for attributes of the specified name was defined, but not for the specified type of declaration. Typically encountered when trying to apply a VAR attribute handler to a subroutine, or a SCALAR attribute handler to some other type of variable.

  • Declaration of %s attribute in package %s may clash with future reserved word

    A handler for an attributes with an all-lowercase name was declared. An attribute with an all-lowercase name might have a meaning to Perl itself some day, even though most don't yet. Use a mixed-case attribute name, instead.

  • Can't have two ATTR specifiers on one subroutine

    You just can't, okay? Instead, put all the specifications together with commas between them in a single ATTR(specification).

  • Can't autotie a %s

    You can only declare autoties for types "SCALAR" , "ARRAY" , and "HASH" . They're the only things (apart from typeglobs -- which are not declarable) that Perl can tie.

  • Internal error: %s symbol went missing

    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.

  • 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.

AUTHOR

Damian Conway (damian@conway.org). The maintainer of this module is now Rafael Garcia-Suarez (rgarciasuarez@gmail.com).

Maintainer of the CPAN release is Steffen Mueller (smueller@cpan.org). Contact him with technical difficulties with respect to the packaging of the CPAN module.

BUGS

There are undoubtedly serious bugs lurking somewhere in code this funky :-) Bug reports and other feedback are most welcome.

COPYRIGHT AND LICENSE

  1. Copyright (c) 2001-2014, Damian Conway. All Rights Reserved.
  2. This module is free software. It may be used, redistributed
  3. and/or modified under the same terms as Perl itself.