ATTRIBUTE::HANDLERS(3pm)
okay bestie, welcome to the Attribute::Handlers(3pm) page π β this is the one about making attribute handlers way simpler.
π NAME π
Attribute::Handlers - Simpler definition of attribute handlers
π VERSION π
This document describes version 1.03 of Attribute::Handlers.
β¨ SYNOPSIS β¨
Here's the vibe check in code form, bestie:
package MyClass;
require 5.006;
use Attribute::Handlers;
no warnings 'redefine';
sub Good : ATTR(SCALAR) {
my ($package, $symbol, $referent, $attr, $data) = @_;
# Invoked for any scalar variable with a :Good attribute,
# provided the variable was declared in MyClass (or
# a derived class) or typed to MyClass.
# Do whatever to $referent here (executed in CHECK phase).
...
}
sub Bad : ATTR(SCALAR) {
# Invoked for any scalar variable with a :Bad attribute,
# provided the variable was declared in MyClass (or
# a derived class) or typed to MyClass.
...
}
sub Good : ATTR(ARRAY) {
# Invoked for any array variable with a :Good attribute,
# provided the variable was declared in MyClass (or
# a derived class) or typed to MyClass.
...
}
sub Good : ATTR(HASH) {
# Invoked for any hash variable with a :Good attribute,
# provided the variable was declared in MyClass (or
# a derived class) or typed to MyClass.
...
}
sub Ugly : ATTR(CODE) {
# Invoked for any subroutine declared in MyClass (or a
# derived class) with an :Ugly attribute.
...
}
sub Omni : ATTR {
# Invoked for any scalar, array, hash, or subroutine
# with an :Omni attribute, provided the variable or
# subroutine was declared in MyClass (or a derived class)
# or the variable was typed to MyClass.
# Use ref($_[2]) to determine what kind of referent it was.
...
}
use Attribute::Handlers autotie => { Cycle => Tie::Cycle };
my $next : Cycle(['A'..'Z']);
πΈ DESCRIPTION πΈ
This module, when inherited by a package, lets that package's class 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. Those handlers then get called in one of the compilation phases β i.e. in a BEGIN, CHECK, INIT, or END block. Periodt.
π¨ Tiny caveat, bestie: 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:
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 a handler for the attribute :Loud in the class LoudDecl. Thereafter, any subroutine declared with a :Loud attribute in the class LoudDecl:
package LoudDecl;
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:
package LoudDecl;
my $foo :Loud;
my @foo :Loud;
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. iykyk π
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:
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:
sub foo :Loud(till=>ears=>are=>bleeding) {...}
sub foo :Loud(qw/till ears are bleeding/) {...}
sub foo :Loud(qw/till, ears, are, bleeding/) {...}
sub foo :Loud(till,ears,are,bleeding) {...}
causes it to pass ['till','ears','are','bleeding'] as the handler's data argument. While:
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:
sub foo :Loud(my,ears,are,bleeding) {...}
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:
package OtherClass;
my LoudDecl $loudobj : Loud;
my LoudDecl @loudobjs : Loud;
my LoudDecl %loudobjex : Loud;
causes the LoudDecl::Loud handler to be invoked β even if OtherClass also defines a handler for :Loud attributes. Slay inheritance moment.
π 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:
package LoudDecl;
sub RealLoud :ATTR(SCALAR) { print "Yeeeeow!" }
creates an attribute handler that applies only to scalars:
package Painful;
use base LoudDecl;
my $metal : RealLoud; # invokes &LoudDecl::RealLoud
my @metal : RealLoud; # error: unknown attribute
my %metal : RealLoud; # error: unknown attribute
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):
package LoudDecl;
use Attribute::Handlers;
no warnings 'redefine';
sub RealLoud :ATTR(SCALAR) { print "Yeeeeow!" }
sub RealLoud :ATTR(ARRAY) { print "Urrrrrrrrrr!" }
sub RealLoud :ATTR(HASH) { print "Arrrrrgggghhhhhh!" }
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:
package LoudDecl;
use Attribute::Handlers;
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:
sub Raw : ATTR(RAWDATA) {...}
sub Nekkid : ATTR(SCALAR,RAWDATA) {...}
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:
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:
sub Early :ATTR(SCALAR,BEGIN) {...}
sub Normal :ATTR(SCALAR,CHECK) {...}
sub Late :ATTR(SCALAR,INIT) {...}
sub Final :ATTR(SCALAR,END) {...}
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:
use Attribute::Handlers;
use Tie::Cycle;
sub UNIVERSAL::Cycle : ATTR(SCALAR) {
my ($package, $symbol, $referent, $attr, $data, $phase) = @_;
$data = [ $data ] unless ref $data eq 'ARRAY';
tie $$referent, 'Tie::Cycle', $data;
}
# and thereafter...
package main;
my $next : Cycle('A'..'Z'); # $next is now a tied variable
while (<>) {
print $next;
}
So like, here's the β¨sitchβ¨: because the Cycle attribute grabs its args through the $data variable, if you hand it a list of arguments, $data is gonna be a single array reference β like one whole array ref, that's it. But if it only gets one argument, $data is just that argument, straight up. And since Tie::Cycle requires its cycling values as an array reference, that means we gotta wrap any non-array-reference args in an array constructor:
$data = [ $data ] unless ref $data eq 'ARRAY';
But ngl, most of the time it's the other way around π« β the tieable class wants its args as a flattened list, so the attribute ends up looking like this:
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 pattern is SO widely applicable β like, genuinely iconic β that Attribute::Handlers gives you a way to automate the whole thing: just say 'autotie' in the use Attribute::Handlers statement π. So our cycling example could also be written as:
use Attribute::Handlers autotie => { Cycle => 'Tie::Cycle' };
# and thereafter...
package main;
my $next : Cycle(['A'..'Z']); # $next is now a tied variable
while (<>) {
print $next;
}
Heads up bestie π’ β now we have to pass the cycling values as an array reference, because the autotie mechanism hands tie a list of arguments as a list (like in the Tie::Whatever example above), not as an array reference (like in the original Tie::Cycle example at the top of the section). Different vibe, different wrapping. π«Ά
The argument after 'autotie' is a reference to a hash where every key is the name of an attribute being created, and every value is the class that variables with that attribute should be tied to.
And the best part? You don't have to import the Tie::Cycle module anymore β Attribute::Handlers handles all of that automagically β¨. You can even pass arguments to the module's import subroutine by just tacking them onto the end of the class name. Like, for example:
use Attribute::Handlers
autotie => { Dir => 'Tie::Dir qw(DIR_UNLINK)' };
If the attribute name is unqualified, the attribute gets installed in the current package. Otherwise it's installed in the qualifier's package. Observe π¦:
package Here;
use Attribute::Handlers autotie => {
Other::Good => Tie::SecureHash, # tie attr installed in Other::
Bad => Tie::Taxes, # tie attr installed in Here::
UNIVERSAL::Ugly => Software::Patent # tie attr installed everywhere
};
Autoties are most commonly used in the module that they actually tie to, and they need to export their attributes to any module that calls them. To make that easy, Attribute::Handlers recognizes a special "pseudo-class" β "__CALLER__" β which you can specify as the qualifier of an attribute:
package Tie::Me::Kangaroo::Down::Sport;
use Attribute::Handlers autotie =>
{ '__CALLER__::Roo' => __PACKAGE__ };
This makes Attribute::Handlers define the "Roo" attribute in whatever package imports the Tie::Me::Kangaroo::Down::Sport module π
β οΈ Lowkey important: you gotta quote the __CALLER__::Roo identifier, because a bug in perl 5.8 will refuse to parse it and throw some unknown error at you. Not a vibe. Quote it, always. π
π
Passing the tied object to tie
Sometimes β not always, but sometimes β it's genuinely important to pass a reference to the object being tied to the TIESCALAR, TIEHASH, etc. that's doing the tying.
The autotie mechanism supports this too, bestie. The following code:
use Attribute::Handlers autotieref => { Selfish => Tie::Selfish };
my $var : Selfish(@args);
has exactly the same effect as:
tie my $var, 'Tie::Selfish', @args;
But when "autotieref" is used instead of "autotie":
use Attribute::Handlers autotieref => { Selfish => Tie::Selfish };
my $var : Selfish(@args);
the effect is to pass the tie call an extra reference to the variable being tied:
tie my $var, 'Tie::Selfish', \$var, @args;
π EXAMPLES
Okay so if the class from "SYNOPSIS" were dropped into the MyClass.pm module, then this code right here:
package main;
use MyClass;
my MyClass $slr :Good :Bad(1**1-1) :Omni(-vorous);
package SomeOtherClass;
use base MyClass;
sub tent { 'acle' }
sub fn :Ugly(sister) :Omni('po',tent()) {...}
my @arr :Good :Omni(s/cie/nt/);
my %hsh :Good(q/bye/) :Omni(q/bus/);
would cause the following handlers to be invoked π₯ (brace yourself, it's a lot, but every single one matters):
# my MyClass $slr :Good :Bad(1**1-1) :Omni(-vorous);
MyClass::Good:ATTR(SCALAR)( 'MyClass', # class
'LEXICAL', # no typeglob
\$slr, # referent
'Good', # attr name
undef # no attr data
'CHECK', # compiler phase
);
MyClass::Bad:ATTR(SCALAR)( 'MyClass', # class
'LEXICAL', # no typeglob
\$slr, # referent
'Bad', # attr name
0 # eval'd attr data
'CHECK', # compiler phase
);
MyClass::Omni:ATTR(SCALAR)( 'MyClass', # class
'LEXICAL', # no typeglob
\$slr, # referent
'Omni', # attr name
'-vorous' # eval'd attr data
'CHECK', # compiler phase
);
# sub fn :Ugly(sister) :Omni('po',tent()) {...}
MyClass::UGLY:ATTR(CODE)( 'SomeOtherClass', # class
\*SomeOtherClass::fn, # typeglob
\&SomeOtherClass::fn, # referent
'Ugly', # attr name
'sister' # eval'd attr data
'CHECK', # compiler phase
);
MyClass::Omni:ATTR(CODE)( 'SomeOtherClass', # class
\*SomeOtherClass::fn, # typeglob
\&SomeOtherClass::fn, # referent
'Omni', # attr name
['po','acle'] # eval'd attr data
'CHECK', # compiler phase
);
# my @arr :Good :Omni(s/cie/nt/);
MyClass::Good:ATTR(ARRAY)( 'SomeOtherClass', # class
'LEXICAL', # no typeglob
\@arr, # referent
'Good', # attr name
undef # no attr data
'CHECK', # compiler phase
);
MyClass::Omni:ATTR(ARRAY)( 'SomeOtherClass', # class
'LEXICAL', # no typeglob
\@arr, # referent
'Omni', # attr name
"" # eval'd attr data
'CHECK', # compiler phase
);
# my %hsh :Good(q/bye) :Omni(q/bus/);
MyClass::Good:ATTR(HASH)( 'SomeOtherClass', # class
'LEXICAL', # no typeglob
\%hsh, # referent
'Good', # attr name
'q/bye' # raw attr data
'CHECK', # compiler phase
);
MyClass::Omni:ATTR(HASH)( 'SomeOtherClass', # class
'LEXICAL', # no typeglob
\%hsh, # referent
'Omni', # attr name
'bus' # eval'd attr data
'CHECK', # compiler phase
);
And listen β installing handlers into UNIVERSAL makes them... err... universal πβ¨. Key move. For example:
package Descriptions;
use Attribute::Handlers;
my %name;
sub name { return $name{$_[2]}||*{$_[1]}{NAME} }
sub UNIVERSAL::Name :ATTR {
$name{$_[2]} = $_[4];
}
sub UNIVERSAL::Purpose :ATTR {
print STDERR "Purpose of ", &name, " is $_[4]\n";
}
sub UNIVERSAL::Unit :ATTR {
print STDERR &name, " measured in $_[4]\n";
}
lets you write this absolute slay:
use Descriptions;
my $capacity : Name(capacity)
: Purpose(to store max storage capacity for files)
: Unit(Gb);
package Other;
sub foo : Purpose(to foo all data before barring it) { }
# etc.
π§° UTILITY FUNCTIONS
This module offers exactly one utility function, findsym(). One. Singular. Iconic minimalism. π
findsym
my $symbol = Attribute::Handlers::findsym($package, $referent);
The function looks in the symbol table of $package for the typeglob of $referent, which is a reference to a variable or subroutine (SCALAR, ARRAY, HASH, or CODE). If it finds that typeglob, it hands it right back to you π. Otherwise, it returns undef β no typeglob for you, bestie. π
Oh and also β "findsym" memoizes the typeglobs it's already successfully found before, so subsequent calls with the same arguments should be much faster. Caching queen behavior fr fr. β‘
π DIAGNOSTICS π
okay bestie, this is the part where Perl looks you dead in the eye and tells you what went wrong. every single one of these messages is listed below, so when you see one in the wild you'll know exactly what's up. let's go π
"Bad attribute type: ATTR(%s)"β you wrote an attribute handler using:ATTR(ref_type), but the type of referent you told it to handle is not one of the five allowed types:"SCALAR","ARRAY","HASH","CODE", or"ANY". that's it. those five. no extras, no vibes-based alternatives π"Attribute handler %s doesn't handle %s attributes"β so you did define a handler for attributes with that name, but not for that specific type of declaration. classic scenario: you try to slap a"VAR"attribute handler onto a subroutine, or a"SCALAR"attribute handler onto some other kind of variable. wrong door, babe πͺ"Declaration of %s attribute in package %s may clash with future reserved word"β you declared a handler for an attribute whose name is all lowercase. lowkey a risk, because an all-lowercase attribute name might mean something to Perl itself one day (most don't yet, but still). the fix is cute and easy: use a mixed-case attribute name instead β¨"Can't have two ATTR specifiers on one subroutine"β because you literally cannot, okay? π instead, put all the specifications together, commas between them, inside a singleATTR(specification)."Can't autotie a %s"β you can only declare autoties for the types"SCALAR","ARRAY", and"HASH". those are the only things (apart from typeglobs β which, ngl, 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 stopped existing somewhere between the point it was declared and the point where its attribute handler(s) would have been called."Won't be able to apply END handler"β you defined anENDhandler for an attribute that's being applied to a lexical variable. since that variable may not be available duringEND, this won't happen. soz π«
π 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). hit him up with technical difficulties with respect to the packaging of the CPAN module π¬
π¦ BUGS π¦
there are undoubtedly serious bugs lurking somewhere in code this funky :-) β like, undoubtedly, bestie, it's giving "we know" π. bug reports and other feedback are most welcome, fr fr π
π COPYRIGHT AND LICENSE π
Copyright (c) 2001-2014, Damian Conway. All Rights Reserved.
This module is free software. It may be used, redistributed
and/or modified under the same terms as Perl itself.
aaaand that's the whole page, you made it to the end, iconic behavior honestly π this was perl v5.42.3, dated 2026-11-03, and the page is Attribu...Handlers(3pm) β go forth and attribute responsibly, bestie πβ¨
π¦ where this page comes from
- alpine 3.24: perl-doc 5.42.3-r0 Β· Artistic-1.0-Perl OR GPL-1.0-or-later
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash-1017 on : a language model's rewrite of the original, under its terms