ATTRIBUTE::HANDLERS(3perl)

๐Ÿ’– NAME ๐Ÿ’–

Attribute::Handlers โ€” simpler definition of attribute handlers, bestie. Like, actually simpler. Fr fr.


๐ŸŒธ VERSION ๐ŸŒธ

This document describes version 1.03 of Attribute::Handlers. Yes queen, 1.03.


โœจ SYNOPSIS โœจ

okay so here's the vibe, look at this:

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']);

slay. okay moving on ๐Ÿ’…


๐Ÿ‘‘ DESCRIPTION ๐Ÿ‘‘

So. This module, when it gets inherited by a package, lets that package's class define attribute handler subroutines for specific attributes. Variables and subroutines that get defined later in that package โ€” or in packages derived from that package โ€” can be given attributes with the same names as the attribute handler subroutines. And then those handlers get 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. Sorry babe ๐Ÿ’€)

To create a handler, you define it as a subroutine with the same name as the desired attribute, and you declare the subroutine itself with the attribute :ATTR. Like this:

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. After that, any subroutine declared with a :Loud attribute in the class LoudDecl:

package LoudDecl;

sub foo: Loud {...}

causes the above handler to be invoked, and it gets passed this whole roster:

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

Same energy for variables, btw. Declaring any variables with the :Loud attribute inside 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, obviously, that $_[2] will be a reference to the variable instead. ๐Ÿซถ

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, bestie, it's giving family tree ๐ŸŒˆ).

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'. Anonymous but iconic ๐Ÿ™ˆ

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" below, iykyk). 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 <em>inside</em> the standard array reference that says "yeah interpretation worked ๐Ÿ’…".

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. not me getting raw strings ๐Ÿ˜ญ

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). The type said periodt, and the type wins ๐Ÿ‘‘


๐ŸŒˆ 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, no cap:

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. Same thing, different outfit ๐Ÿ’…)


๐Ÿงš 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. Rude of it, honestly.

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"

Don't overthink it, it just hands you the raw string bestie ๐Ÿ“


๐ŸŒธ 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. Perfect timing honestly, main character scheduling โœจ

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. Early bird behavior, no waiting ๐Ÿ’€

๐ŸŽ€ Attributes as "tie" interfaces ๐ŸŽ€

Attributes make an excellent and intuitive interface through which to tie variables. Obsessed, actually. 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;
}

<span>more parts coming bestie, don't go anywhere ๐Ÿ’–</span>

okay so real talk bestie โ€” because the "Cycle" attribute gets its args handed to it in the $data variable, there's a lil catch: if the attribute was given a list of args, $data shows up as a single array ref; but if it just got one arg, $data is literally that one arg directly. And since Tie::Cycle requires its cycling values as an array ref, that means we have to wrap any non-array-ref args in an array constructor:

$data = [ $data ] unless ref $data eq 'ARRAY';

But usually it's the opposite situation ๐Ÿ˜ญ โ€” the tieable class wants its args as a flattened list, so the attribute looks like this instead:

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 sooooo broadly useful that Attribute::Handlers just goes ahead and automates the whole thing for you: you write 'autotie' in your "use Attribute::Handlers" statement. โœจ So the cycling example could also be written like:

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 tho ๐Ÿ‘€ โ€” now we have to pass the cycling values as an array ref, because the "autotie" mechanism hands tie a list of args as a list (same as the Tie::Whatever example above), not as an array ref (which is what the original Tie::Cycle example at the top of this section did). Different vibe, different wrapping, iykyk.

So the arg after 'autotie'? It's a reference to a hash where every key is the name of an attribute getting created, and every value is the class that variables with that attribute should get tied to. ๐Ÿ’…

And boom โ€” you don't even need to import the Tie::Cycle module anymore, Attribute::Handlers handles that automagically for you. You can even pass args to the module's "import" subroutine by just appending them to the class name. Like:

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

If the attribute name is unqualified, it gets installed in the current package. If it is qualified, it goes in the qualifier's package instead:

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
};

๐ŸŒธ Passing the tied object to "tie" ๐ŸŒธ

Sometimes it actually matters that you pass a reference to the object being tied into the TIESCALAR, TIEHASH, etc. that does the tying. ๐Ÿซถ

The "autotie" mechanism supports this too. So this code:

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

does exactly the same thing as:

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

But when you use "autotieref" instead of "autotie":

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

the effect is that it hands the tie call an extra reference to the variable being tied:

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

๐ŸŽ€ EXAMPLES ๐ŸŽ€

So if the class shown back in "SYNOPSIS" lived inside a MyClass.pm module, then this code:

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 make the following handlers get invoked ๐ŸŽฌ:

# 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 installing handlers into UNIVERSAL makes themโ€ฆ errโ€ฆ universal. ๐Ÿ˜Œ Like:

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 stuff like this:

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 gives you exactly one utility function, and it's findsym(). ๐Ÿ’…

findsym

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

So what does it do bestie? It digs through the symbol table of $package looking for the typeglob for $referent โ€” and $referent is a reference to a variable or subroutine (SCALAR, ARRAY, HASH, or CODE). Find it? It returns it. ๐ŸŒŸ Don't find it? It returns undef. ๐Ÿ™ˆ

Oh and ngl there's a lil glow-up happening under the hood: "findsym" memoizes the typeglobs it already successfully found, so calling it again with the same args should be way faster. Efficiency queen. ๐Ÿ‘‘

๐Ÿ’ฅ DIAGNOSTICS ๐Ÿ’ฅ

okay so if Perl starts yelling, here's what it's actually tryna tell you, bestie. read the vibes, fix the code, slay.

  • Bad attribute type: ATTR(%s) โ€” so you set up an attribute handler with :ATTR(ref_type), but the type of referent you told it to handle is not one of the five allowed: SCALAR, ARRAY, HASH, CODE, or ANY. that's it. those are the only options. pick one, periodt. ๐Ÿ’…
  • Attribute handler %s doesn't handle %s attributes โ€” a handler was defined for attributes with that name, but not for that type of declaration. this usually pops up when you're trying to apply a VAR attribute handler to a subroutine, or a SCALAR attribute handler to some other kind of variable. mismatch energy, fr fr. ๐Ÿ™ˆ
  • Declaration of %s attribute in package %s may clash with future reserved word โ€” you declared a handler for an attribute with an all-lowercase name. an all-lowercase attribute might mean something to Perl itself some day, even though most don't yet. so like, use a mixed-case attribute name instead. protect your future self, no cap. ๐Ÿ”ฎ
  • 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). one ATTR, many specs, cute. โœจ
  • 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. sorry babe, that's the limit. ๐ŸŽ€
  • Internal error: %s symbol went missing โ€” something is rotten in the state of the program. an attributed subroutine just... ceased to exist between the point it was declared and the point at which its attribute handler(s) would have been called. literally vanished. spooky, lowkey. ๐Ÿ’€
  • Won't be able to apply END handler โ€” you defined an END handler for an attribute that's being applied to a lexical variable. since the variable may not be available during END, this won't happen. so that handler is not getting its main character moment, unfortunately. ๐Ÿ˜ญ

๐Ÿ‘‘ 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. he's the packaging plug. ๐Ÿซถ


๐Ÿ› BUGS ๐Ÿ›

there are undoubtedly serious bugs lurking somewhere in code this funky :-) bug reports and other feedback are most welcome. like genuinely, slide into the feedback inbox, we wanna hear it. ๐Ÿ’Œ


         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.

and that's the whole page, bestie!! ๐Ÿฆ‹ this was Attrib...andlers(3perl) from perl v5.44.0, dated 2026-10-17. go forth and attribute responsibly. mwah. ๐Ÿ’–โœจ๐ŸŒธ

๐Ÿ“ฆ where this page comes from
  • arch rolling: perl 5.44.0-1 ยท Artistic-1.0-Perl AND GPL-1.0-or-later
  • ๐Ÿ’– girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms