attributes(3pm)
π attributes β get/set subroutine or variable attributes π
okay bestie, welcome to attributes(3pm) from the Perl Programmers Reference Guide β yes, the 3pm shelf, the perl-modules one, you know the vibe. This is the page that lets your subs and your variables wear little accessories. Cute little labels. : method, : Bent, the whole thing. It's giving "my code has a personality and the personality is decorated." π
β¨ SYNOPSIS β¨
okay so this is literally what it looks like in the wild, no edits, take it in:
sub foo : method ;
my ($x,@y,%z) : Bent = 1;
my $s = sub : method { ... };
use attributes (); # optional, to get subroutine declarations
my @attrlist = attributes::get(\&foo);
use attributes 'get'; # import the attributes::get subroutine
my @attrlist = get \&foo;
look at that first line. sub foo : method ; β the colon is doing the heavy lifting, the method is the accessory, and foo is just standing there looking iconic. π₯
then my ($x,@y,%z) : Bent = 1; β yes, you can slap an attribute on a whole lil declaration group of a scalar, an array, and a hash all at once and then assign 1 to them. the : Bent is attached to the declaration, and the = 1 is just doing its normal assignment thing.
then my $s = sub : method { ... }; β anonymous sub, also accessorised, also thriving. we love a main character coderef. π
and for the getting the attributes back part, you've got two whole routes:
- the fully-qualified
attributes::getroute βuse attributes ();is optional here and it's specifically there so you get the subroutine declarations, thenmy @attrlist = attributes::get(\&foo);grabs the attribute list off\&fooπ¦ - the imported route β
use attributes 'get';imports theattributes::getsubroutine into your namespace, so you can just saymy @attrlist = get \&foo;and skip the long name entirely. slay, less typing, same result π
both of those hand you back @attrlist, which is exactly what it sounds like: the list of attributes. πΈ
there's more coming, bestie β this was just the vibe check and the synopsis. the description and all the options are up next, and there are a lot of them, so hydrate before you scroll. π
π DESCRIPTION π
okay so bestie, listen β subroutine declarations and definitions can optionally have attribute lists attached to them. slay. (variable my declarations can too, but pls read the warning below first, i'm begging π). Perl handles all of this by passing some info about the call site and the thing being declared, along with the attribute list, straight to this module. so like, the first example up in the synopsis is literally equivalent to this:
use attributes __PACKAGE__, \&foo, 'method';
and the second example in the synopsis does basically this:
use attributes ();
my ($x,@y,%z);
attributes::->import(__PACKAGE__, \$x, 'Bent');
attributes::->import(__PACKAGE__, \@y, 'Bent');
attributes::->import(__PACKAGE__, \%z, 'Bent');
($x,@y,%z) = 1;
yes, that's a lot of expansion. it's giving "my mom explaining a meme" energy but it's accurate so π«Ά
WARNING: attribute declarations for variables are still evolving. no cap. the semantics and interfaces of such declarations could change in future versions. they're here for purposes of experimentation with what the semantics ought to be. do not rely on the current implementation of this feature. π
there are only a few attributes currently handled by Perl itself (or directly by this module, depending on how you look at it π). but! package-specific attributes are allowed by an extension mechanism. (see "Package-specific Attribute Handling" below.)
the setting of subroutine attributes happens at compile time. variable attributes in our declarations are also applied at compile time. however β and this is the plot twist β my variables get their attributes applied at run-time. which means you have to reach the run-time component of the my before those attributes will get applied. for example:
my $x : Bent = 42 if 0;
will neither assign 42 to $x nor apply the Bent attribute to the variable. so iconic of it to do literally nothing β¨
an attempt to set an unrecognized attribute is a fatal error. (the error is trappable, but it still stops the compilation within that eval.) and setting an attribute with a name that's all lowercase letters that's not a built-in attribute (such as foo) will result in a warning with -w or use warnings 'reserved'. consider yourself warned bestie π
π What import does π
in the description it's mentioned that
sub foo : method;
is equivalent to
use attributes __PACKAGE__, \&foo, 'method';
as you might know, this calls the import function of attributes at compile time with these parameters: 'attributes', the caller's package name, the reference to the code and 'method'.
attributes->import( __PACKAGE__, \&foo, 'method' );
so you wanna know what import actually does? valid question, main character energy π
first of all import gets the type of the third parameter ('CODE' in this case). attributes.pm checks if there's a subroutine called MODIFY_<reftype>_ATTRIBUTES in the caller's namespace (here: 'main'). in this case a subroutine MODIFY_CODE_ATTRIBUTES is required. then this method is called to check if you've used a "bad attribute". the subroutine call in this example would look like
MODIFY_CODE_ATTRIBUTES( 'main', \&foo, 'method' );
MODIFY_<reftype>_ATTRIBUTES has to return a list of all "bad attributes". if there are any bad attributes, import croaks. no thoughts, just croak πΈ
(see "Package-specific Attribute Handling" below.)
π Built-in Attributes π
the following are the built-in attributes for subroutines:
lvalueβ indicates that the referenced subroutine is a valid lvalue and can be assigned to. the subroutine must return a modifiable value such as a scalar variable, as described in perlsub.
this module allows one to set this attribute on a subroutine that's already defined. for Perl subroutines (XSUBs are fine), it may or may not do what you want, depending on the code inside the subroutine, with details subject to change in future Perl versions. you may run into problems with lvalue context not being propagated properly into the subroutine, or maybe even assertion failures π. for this reason, a warning is emitted if warnings are enabled. in other words, you should only do this if you really know what you're doing. you have been warned. fr fr this one is dangerous.
methodβ indicates that the referenced subroutine is a method. a subroutine so marked won't trigger the"Ambiguous call resolved as CORE::%s"warning. slay, no ambiguity πprototype(..)β theprototypeattribute is an alternate means of specifying a prototype on a sub. the desired prototype goes inside the parens.
the prototype from the attribute is assigned to the sub immediately after the prototype from the sub, which means that if both are declared at the same time, the traditionally defined prototype is ignored. in other words, sub foo($$) : prototype(@) {} is indistinguishable from sub foo(@){}. the attribute ate and left no crumbs π₯
if illegalproto warnings are enabled, the prototype declared inside this attribute will be sanity checked at compile time.
constβ this experimental attribute, introduced in Perl 5.22, only applies to anonymous subroutines. it causes the subroutine to be called as soon as thesubexpression is evaluated. the return value is captured and turned into a constant subroutine. cute little constant moment π§
the following are the built-in attributes for variables:
sharedβ indicates that the referenced variable can be shared across different threads when used in conjunction with the threads and threads::shared modules. sharing is caring bestie π«Ά
β Available Subroutines β
the following subroutines are available for general use once this module has been loaded:
getβ this routine expects a single parameter β a reference to a subroutine or variable. it returns a list of attributes, which may be empty. if passed invalid arguments, it usesdie()(viaCarp::croak) to raise a fatal exception. if it can find an appropriate package name for a class method lookup, it will include the results from aFETCH_type_ATTRIBUTEScall in its return list, as described in "Package-specific Attribute Handling" below. otherwise, only built-in attributes will be returned.reftypeβ this routine expects a single parameter β a reference to a subroutine or variable. it returns the built-in type of the referenced variable, ignoring any package into which it might have been blessed. this can be useful for determining the type value which forms part of the method names described in "Package-specific Attribute Handling" below.
note that these routines are not exported by default. you gotta ask nicely (or use the exports section, iykyk π).
π¦ Package-specific Attribute Handling π¦
WARNING: the mechanisms described here are still experimental. do not rely on the current implementation. in particular, there is no provision for applying package attributes to 'cloned' copies of subroutines used as closures. (see "Making References" in perlref for information on closures.) package-specific attribute handling may change incompatibly in a future release. this is your reminder that experimental means EXPERIMENTAL, bestie π
when an attribute list is present in a declaration, a check is made to see whether an attribute 'modify' handler is present in the appropriate package (or its @ISA inheritance tree). similarly, when attributes::get is called on a valid reference, a check is made for an appropriate attribute 'fetch' handler. see "EXAMPLES" to see how the "appropriate package" determination works.
the handler names are based on the underlying type of the variable being declared or of the reference passed. because these attributes are associated with subroutine or variable declarations, this deliberately ignores any possibility of being blessed into some package. thus, a subroutine declaration uses CODE as its type, and even a blessed hash reference uses HASH as its type. no package energy allowed here π«
the class methods invoked for modifying and fetching are these:
FETCH_type_ATTRIBUTES
this method is called with two arguments: the relevant package name, and a reference to a variable or subroutine for which package-defined attributes are desired. the expected return value is a list of associated attributes. this list may be empty. (empty is a valid vibe β¨)
MODIFY_type_ATTRIBUTES
this method is called with two fixed arguments, followed by the list of attributes from the relevant declaration. the two fixed arguments are the relevant package name and a reference to the declared subroutine or variable. the expected return value is a list of attributes which were not recognized by this handler. note that this allows for a derived class to delegate a call to its base class, and then only examine the attributes which the base class didn't already handle for it. teamwork makes the dream work π€
the call to this method is currently made during the processing of the declaration. in particular, this means that a subroutine reference will probably be for an undefined subroutine, even if this declaration is actually part of the definition. yeah. it's a whole thing. π
calling attributes::get() from within the scope of a null package declaration package ; for an unblessed variable reference will not provide any starting package name for the 'fetch' method lookup. thus, this circumstance will not result in a method call for package-defined attributes. a named subroutine knows to which symbol table entry it belongs (or originally belonged), and it will use the corresponding package. an anonymous subroutine knows the package name into which it was compiled (unless it was also compiled with a null package declaration), and so it will use that package name. so like, it knows where it came from. self-aware king π
π Syntax of Attribute Lists π
an attribute list is a sequence of attribute specifications, separated by whitespace or a colon (with optional whitespace). each attribute specification is a simple name, optionally followed by a parenthesised parameter list. if such a parameter list is present, it's scanned past as for the rules for the q() operator. (see "Quote and Quote-like Operators" in perlop.) the parameter list is passed as it was found, however, and not as per q().
some examples of syntactically valid attribute lists:
switch(10,foo(7,3)) : expensive
Ugly('\(") :Bad
_5x5
lvalue method
some examples of syntactically invalid attribute lists (with annotation):
switch(10,foo() # ()-string not balanced
Ugly('(') # ()-string not balanced
5x5 # "5x5" not a valid identifier
Y2::north # "Y2::north" not a simple identifier
foo + bar # "+" neither a colon nor whitespace
learn from their mistakes bestie, they're giving cautionary tale π
β¨ EXPORTS β¨
Default exports
none. nada. zero. we give you nothing by default and you'll deal π
Available exports
the routines get and reftype are exportable. those two? iconic. take them, they're yours π
Export tags defined
the :ALL tag will get all of the above exports. one tag to rule them all π
β¨ EXAMPLES β¨
Okay bestie, here are some syntactically valid declarations, with annotations showing how perl internally resolves them into use attributes invocations. π
These are mostly iconic for seeing how the "appropriate package" gets found for the possible method lookups for package-defined attributes.
- Code:
package Canine;
package Dog;
my Canine $spot : Watchful ;
Effect:
use attributes ();
attributes::->import(Canine => \$spot, "Watchful");
- Code:
package Felis;
my $cat : Nervous;
Effect:
use attributes ();
attributes::->import(Felis => \$cat, "Nervous");
- Code:
package X;
sub foo : lvalue ;
Effect:
use attributes X => \&foo, "lvalue";
- Code:
package X;
sub Y::x : lvalue { 1 }
Effect:
use attributes Y => \&Y::x, "lvalue";
- Code:
package X;
sub foo { 1 }
package Y;
BEGIN { *bar = \&X::foo; }
package Z;
sub Y::bar : lvalue ;
Effect:
use attributes X => \&X::foo, "lvalue";
This last example is purely for purposes of completeness. You should not be trying to mess with the attributes of something in a package that's not your own. π¨
π MORE EXAMPLES π
- Code:
sub MODIFY_CODE_ATTRIBUTES {
my ($class,$code,@attrs) = @_;
my $allowed = 'MyAttribute';
my @bad = grep { $_ ne $allowed } @attrs;
return @bad;
}
sub foo : MyAttribute {
print "foo\n";
}
This example runs. At compile time MODIFY_CODE_ATTRIBUTES is called. In that subroutine, we check if any attribute is disallowed and we return a list of these "bad attributes".
As we return an empty list, everything is fine. β
- Code:
sub MODIFY_CODE_ATTRIBUTES {
my ($class,$code,@attrs) = @_;
my $allowed = 'MyAttribute';
my @bad = grep{ $_ ne $allowed }@attrs;
return @bad;
}
sub foo : MyAttribute Test {
print "foo\n";
}
This example is aborted at compile time as we use the attribute "Test" which isn't allowed. MODIFY_CODE_ATTRIBUTES returns a list that contains a single element ('Test'). π
π¦ SEE ALSO π¦
For details on the basic declarations, check "Private Variables via my()" in perlsub and "Subroutine Attributes" in perlsub. For details on the normal invocation mechanism, see "use" in perlfunc. π«Ά
That's the whole page, bestie! π This one comes from attributes(3pm) via perl v5.42.3, dated 2026-11-03. Bye, slay, and happy attribute-ing! ππ
π¦ 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