Attribute::Handlers
Implements a simpler definition of attribute handlers. When inherited by a package, Attribute::Handlers allows that package’s class to define handler subroutines for specific attributes. When inherited by a package, these handlers will be called by the same names as the original attribute-handling subroutines. Attribute handlers will be called at one of the following compilation phases: BEGIN, CHECK, INIT, or END blocks. Note that Attribute::Handlers is shipped with the Perl source kit as of Version 5.8.
Handlers are defined as subroutines and named as the
desired attribute. In the following example, the attribute is :ATTR
, which lives in a subroutine that’s
called Nate1()
in the HandlerBing
class:
package HandlerBing; use Attribute::Handlers; sub Nate1 :ATTR { my(@attrs) = @_; # We simply want to test by dumping the attributes print "attributes: \n", join("\n", @attrs), "\n"; } # true. 1;
This stub for the HandlerBing class creates a handler for the
attribute :Nate1
. When you want to
use this handler while within HandlerBing, you can do the
following:
sub Nate2 :Nate1 { my (@stuff) = @_; print STDERR "in Nate2 ", join("\n", @stuff), "\n"; }
When you call Nate2
, it
invokes the Nate1
handler and
passes the following elements into the @_
array:
0
The name of the package in which the handler was declared
1
A reference to the symbol table entry (a typeglob) that contains the subroutine
2
A reference to the subroutine
3
The name of the attribute itself
4
Any data associated with ...
Get Perl in a Nutshell, 2nd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.