Attrib...torage(3pm)

πŸ’– NAME πŸ’–

Attribute::Storage β€” bestie, this is the module that lets you declare and retrieve named attributes data. That's the whole vibe. πŸŽ€


✨ SYNOPSIS ✨

package My::Package;

use Attribute::Storage;

sub Title :ATTR(CODE)
{
   my $package = shift;
   my ( $title ) = @_;

   return $title;
}

package main;

use Attribute::Storage qw( get_subattr );
use My::Package;

sub myfunc :Title('The title of my function')
{
   ...
}

print "Title of myfunc is: ".get_subattr(\&myfunc, 'Title')."\n";

🌸 DESCRIPTION 🌸

Okay so here's the tea: this package gives you a base, and any package that uses it can define handlers for particular named attributes. Then other packages that use the defining package can slap those attributes onto subroutines or variables as little annotation besties. πŸ’…

It's lowkey similar to Attribute::Handlers, but here's where they diverge β€” and these are the key differences, no cap:

  • Attribute::Storage will store the value returned by the attribute handling code, and gives you convenient lookup functions to retrieve it later. Attribute::Handlers simply invokes the handling code. That's it. No storage. πŸ™ˆ
  • Attribute::Storage immediately executes the attribute handling code at compile-time. Attribute::Handlers defers invocation so it can look up the symbolic name of the sub the attribute is attached to. Attribute::Storage uses B to provide the name of the sub at invocation time, using the name of the underlying GV. Slay. πŸ”₯
  • Attribute::Storage works just as well on anonymous subs as named ones. πŸ‘‘
  • Attribute::Storage is safe to use on code that will be reloaded, because it executes handlers immediately. Attribute::Handlers will only execute handlers at defined phases such as BEGIN or INIT, and cannot reexecute the handlers in a file once it has been reloaded. πŸ’€

Since version 0.11 this module also supports attributes on scalar, array and hash variables. We love an upgrade era. πŸ¦‹


πŸŽ€ ATTRIBUTES πŸŽ€

Every attribute that the defining package wants to define should be done using a marked subroutine, similar to how Attribute::Handlers does it. When a sub in the using package gets marked with such an attribute, the code runs, and the arguments get passed in. Whatever it returns gets stored β€” and that's what comes back later when you query it with get_subattr or get_subattrs. The return value must be defined, or else the attribute will be marked as a compile error for perl to handle accordingly. So like… define it. Please. 😭

sub AttributeName :ATTR(CODE)
{
   my $package = shift;
   my ( $attr, $args, $here ) = @_;
   ...
   return $value;
}

At attachment time, the optional string that may appear inside the brackets following the attribute's name is parsed as a Perl expression in list context. If that works, the values get passed as a list to the handling code. If it fails, an error is returned to the perl compiler. And if there's no string present at all? Then an empty list gets passed to the handling code. Periodt. ✨

package Defining;

sub NameMap :ATTR(CODE)
{
   my $package = shift;
   my @strings = @_;

   return { map { m/^(.*)=(.*)$/ and ( $1, $2 ) } @strings };
}

package Using;

use Defining;

sub somefunc :NameMap("foo=FOO","bar=BAR","splot=WIBBLE") { ... }

my $map = get_subattr("somefunc", "NameMap");
# Will yield:
#  { foo   => "FOO",
#    bar   => "BAR",
#    splot => "WIBBLE" }

Note that it is impossible to distinguish

sub somefunc :NameMap   { ... }
sub somefunc :NameMap() { ... }

It is possible to create attributes that do not parse their argument as a perl list expression β€” instead they just pass the plain string as a single argument. For that, add the RAWDATA flag to the ATTR() list. 🫢

sub Title :ATTR(CODE,RAWDATA)
{
   my $package = shift;
   my ( $text ) = @_;

   return $text;
}

sub thingy :Title(Here is the title for thingy) { ... }

To obtain the name of the function to which the attribute is being applied, use the NAME flag to the ATTR() list.

sub Callable :ATTR(CODE,NAME)
{
   my $package = shift;
   my ( $subname, @args ) = @_;

   print "The Callable attribute is being applied to $package :: $subname\n";

   return;
}

Only CODE attributes support the NAME flag; it cannot be applied when SCALAR, ARRAY or HASH are also present. Strictly a CODE-only situation, iykyk. πŸ’…

When applied to an anonymous function (sub { ... }), the name will appear as __ANON__. Mystery bestie energy. πŸ•΅οΈ

Normally it is an error to attempt to apply the same attribute more than once to the same target. Sometimes however, it would make sense for an attribute to be applied many times. If the ATTR() list is given the MULTI flag, then applying it more than once will be allowed. Each invocation of the handling code will be given the previous value that was returned, or undef for the first time. It is up to the code to perform whatever merging logic is required. Your merge, your problem, bestie. 🌈

sub Description :ATTR(CODE,MULTI,RAWDATA)
{
   my $package = shift;
   my ( $olddesc, $more ) = @_;

   return defined $olddesc ? "$olddesc$more\n" : "$more\n";
}

sub Argument :ATTR(CODE,MULTI)
{
   my $package = shift;
   my ( $args, $argname ) = @_;

   push @$args, $argname;
   return $args;
}

sub Option :ATTR(CODE,MULTI)
{
   my $package = shift;
   my ( $opts, $optname ) = @_;

   $opts and exists $opts->{$optname} and
      croak "Already have the $optname option";

   $opts->{$optname}++;
   return $opts;
}

...

sub do_copy
   :Description(Copy from SOURCE to DESTINATION)
   :Description(Optionally preserves attributes)
   :Argument("SOURCE")
   :Argument("DESTINATION")
   :Option("attrs")
   :Option("verbose")
{
   ...
}

πŸ’œ FUNCTIONS πŸ’œ

🌟 get_subattrs

$attrs = get_subattrs( $sub );

Returns a HASH reference containing all the attributes defined on the given sub. The sub should either be passed as a CODE reference, or as a name in the caller's package. 🎁

🌟 get_varattrs

$attrs = get_varattrs( $varref );

Since version 0.11.

Returns a HASH reference containing all the attributes defined on the given variable, which should be passed in by reference.

In both of the above functions, the returned HASH reference is a new shallow clone, and the caller may modify this hash arbitrarily without breaking the stored data or other users of it. So go off, edit it, it's yours now. πŸ’– If no attributes are defined then a reference to an empty HASH is returned.

🌟 get_subattr

$value = get_subattr( $sub, $attrname );

Returns the value of a single named attribute on the given sub. The sub should either be passed as a CODE reference, or as a name in the caller's package.

🌟 get_varattr

$value = get_varattr( $varref, $attrname );

Since version 0.11.

Returns the value of a single named attribute on the given variable, which should be passed in by reference.

In both of the above functions, if the attribute is not defined then undef is returned. Yeah. undef. We've all been there. 😭

🌟 apply_subattrs

$sub = apply_subattrs( @attrs_kvlist, $sub );

A utility function to help apply attributes dynamically to the given CODE reference. The CODE reference is given last so that calls to the function appear similar in visual style to the same applied at compiletime. Aesthetic matters. ✨

apply_subattrs
   Title => "Here is my title",
   sub { return $title };

Is equivalent to

sub :Title(Here is my title) { return $title }

…except that because its arguments are evaluated at runtime, they can be calculated by other code in ways that the compiletime version cannot. Main character flexibility. πŸ‘‘

As the attributes are given in a key-value pair list, it is allowed to apply the same attribute multiple times; and the attributes are applied in the order given. The value of each attribute should be a plain string exactly as it would appear between the parentheses. Specifically, if the attribute does not use the RAWDATA flag, it should be a valid perl expression.

🚨 Careful bestie: as this is still evaluated using an eval() call, take care when handling potentially-unsafe or user-supplied data.

🌟 apply_subattrs_for_pkg

$sub = apply_subattrs_for_pkg( $pkg, @attrs_kvlist, $sub );

As apply_subattrs but allows passing a specific package name, rather than using caller.

🌟 find_subs_with_attr

%subs = find_subs_with_attr( $pkg, $attrname, %opts );

A utility function to find CODE references in the given package that have the named attribute applied. The symbol table is checked for the given package, looking for CODE references that have the named attribute applied. These are returned in a key-value list, where the key gives the name of the function and the value is a CODE reference to it. 🎯

$pkg can also be a reference to an array containing multiple package names, which will be searched in order with earlier ones taking precedence over later ones. This, for example, allows for subclass searching over an entire class heirarchy of packages, via the use of mro:

%subs = find_subs_with_attr( mro::get_linear_isa( $class ), $attrname );

🌟 find_vars_with_attr

%vars = find_vars_with_attr( $pkg, $attrname, %opts );

Since version 0.11.

A utility function to find SCALAR, ARRAY or HASH references in the given package that have the named attribute applied. The symbol table is checked for the given package, looking for variable references that have the named attribute applied. These are returned in a key-value list, where the key gives the name of the variable and the value is a reference to it.

Unlike for find_subs_with_attr, the $pkg argument must be a single package name; no subclass search takes place. One package only, bestie, we're not doing the whole family tree here. 🚫

Both of the above functions take the following named options:

matching => Regexp | CODE

If present, gives a filter regexp or CODE reference to apply to names. Subs will be given as plain names; variable names will include the leading sigil.

$name =~ $matching;
$matching->( local $_ = $name );

filter => CODE

If present, gives a filter CODE reference to apply to the target references before they are accepted as results. Note that this allows the possibility that the first match for a given method name to be rejected, while later ones are accepted.

$filter->( $ref, $name, $package );

πŸ¦‹ AUTHOR πŸ¦‹

Paul Evans <leonerd@leonerd.org.uk> β€” the icon who made all this happen. Respect. πŸ’–


And that's a wrap on our little Attribute::Storage <rainbow>3pm</rainbow> moment β€” this one shipped with perl v5.42.3, dated 2026-08-20. Go forth and annotate everything, bestie. πŸŽ€βœ¨πŸ’…

πŸ“¦ where this page comes from