{
    "mode": "perldoc",
    "parameter": "attributes",
    "section": "",
    "url": "https://www.chedong.com/phpMan.php/perldoc/attributes/json",
    "generated": "2026-06-14T13:04:00Z",
    "synopsis": "sub foo : method ;\nmy ($x,@y,%z) : Bent = 1;\nmy $s = sub : method { ... };\nuse attributes ();    # optional, to get subroutine declarations\nmy @attrlist = attributes::get(\\&foo);\nuse attributes 'get'; # import the attributes::get subroutine\nmy @attrlist = get \\&foo;",
    "sections": {
        "NAME": {
            "content": "attributes - get/set subroutine or variable attributes\n",
            "subsections": []
        },
        "SYNOPSIS": {
            "content": "sub foo : method ;\nmy ($x,@y,%z) : Bent = 1;\nmy $s = sub : method { ... };\n\nuse attributes ();    # optional, to get subroutine declarations\nmy @attrlist = attributes::get(\\&foo);\n\nuse attributes 'get'; # import the attributes::get subroutine\nmy @attrlist = get \\&foo;\n",
            "subsections": []
        },
        "DESCRIPTION": {
            "content": "Subroutine declarations and definitions may optionally have attribute lists associated with\nthem. (Variable \"my\" declarations also may, but see the warning below.) Perl handles these\ndeclarations by passing some information about the call site and the thing being declared along\nwith the attribute list to this module. In particular, the first example above is equivalent to\nthe following:\n\nuse attributes PACKAGE, \\&foo, 'method';\n\nThe second example in the synopsis does something equivalent to this:\n\nuse attributes ();\nmy ($x,@y,%z);\nattributes::->import(PACKAGE, \\$x, 'Bent');\nattributes::->import(PACKAGE, \\@y, 'Bent');\nattributes::->import(PACKAGE, \\%z, 'Bent');\n($x,@y,%z) = 1;\n\nYes, that's a lot of expansion.\n\nWARNING: attribute declarations for variables are still evolving. The semantics and interfaces\nof such declarations could change in future versions. They are present for purposes of\nexperimentation with what the semantics ought to be. Do not rely on the current implementation\nof this feature.\n\nThere are only a few attributes currently handled by Perl itself (or directly by this module,\ndepending on how you look at it.) However, package-specific attributes are allowed by an\nextension mechanism. (See \"Package-specific Attribute Handling\" below.)\n\nThe setting of subroutine attributes happens at compile time. Variable attributes in \"our\"\ndeclarations are also applied at compile time. However, \"my\" variables get their attributes\napplied at run-time. This means that you have to *reach* the run-time component of the \"my\"\nbefore those attributes will get applied. For example:\n\nmy $x : Bent = 42 if 0;\n\nwill neither assign 42 to $x *nor* will it apply the \"Bent\" attribute to the variable.\n\nAn attempt to set an unrecognized attribute is a fatal error. (The error is trappable, but it\nstill stops the compilation within that \"eval\".) Setting an attribute with a name that's all\nlowercase letters that's not a built-in attribute (such as \"foo\") will result in a warning with\n-w or \"use warnings 'reserved'\".\n\nWhat \"import\" does\nIn the description it is mentioned that\n\nsub foo : method;\n\nis equivalent to\n\nuse attributes PACKAGE, \\&foo, 'method';\n\nAs you might know this calls the \"import\" function of \"attributes\" at compile time with these\nparameters: 'attributes', the caller's package name, the reference to the code and 'method'.\n\nattributes->import( PACKAGE, \\&foo, 'method' );\n\nSo you want to know what \"import\" actually does?\n\nFirst of all \"import\" gets the type of the third parameter ('CODE' in this case).\n\"attributes.pm\" checks if there is a subroutine called \"MODIFY<reftype>ATTRIBUTES\" in the\ncaller's namespace (here: 'main'). In this case a subroutine \"MODIFYCODEATTRIBUTES\" is\nrequired. Then this method is called to check if you have used a \"bad attribute\". The subroutine\ncall in this example would look like\n\nMODIFYCODEATTRIBUTES( 'main', \\&foo, 'method' );\n\n\"MODIFY<reftype>ATTRIBUTES\" has to return a list of all \"bad attributes\". If there are any bad\nattributes \"import\" croaks.\n\n(See \"Package-specific Attribute Handling\" below.)\n",
            "subsections": [
                {
                    "name": "Built-in Attributes",
                    "content": "The following are the built-in attributes for subroutines:\n\nlvalue\nIndicates that the referenced subroutine is a valid lvalue and can be assigned to. The\nsubroutine must return a modifiable value such as a scalar variable, as described in\nperlsub.\n\nThis module allows one to set this attribute on a subroutine that is already defined. For\nPerl subroutines (XSUBs are fine), it may or may not do what you want, depending on the code\ninside the subroutine, with details subject to change in future Perl versions. You may run\ninto problems with lvalue context not being propagated properly into the subroutine, or\nmaybe even assertion failures. For this reason, a warning is emitted if warnings are\nenabled. In other words, you should only do this if you really know what you are doing. You\nhave been warned.\n\nmethod\nIndicates that the referenced subroutine is a method. A subroutine so marked will not\ntrigger the \"Ambiguous call resolved as CORE::%s\" warning.\n"
                },
                {
                    "name": "prototype",
                    "content": "The \"prototype\" attribute is an alternate means of specifying a prototype on a sub. The\ndesired prototype is within the parens.\n\nThe prototype from the attribute is assigned to the sub immediately after the prototype from\nthe sub, which means that if both are declared at the same time, the traditionally defined\nprototype is ignored. In other words, \"sub foo($$) : prototype(@) {}\" is indistinguishable\nfrom \"sub foo(@){}\".\n\nIf illegalproto warnings are enabled, the prototype declared inside this attribute will be\nsanity checked at compile time.\n\nconst\nThis experimental attribute, introduced in Perl 5.22, only applies to anonymous subroutines.\nIt causes the subroutine to be called as soon as the \"sub\" expression is evaluated. The\nreturn value is captured and turned into a constant subroutine.\n\nThe following are the built-in attributes for variables:\n\nshared\nIndicates that the referenced variable can be shared across different threads when used in\nconjunction with the threads and threads::shared modules.\n"
                },
                {
                    "name": "Available Subroutines",
                    "content": "The following subroutines are available for general use once this module has been loaded:\n\nget This routine expects a single parameter--a reference to a subroutine or variable. It returns\na list of attributes, which may be empty. If passed invalid arguments, it uses die() (via\nCarp::croak) to raise a fatal exception. If it can find an appropriate package name for a\nclass method lookup, it will include the results from a \"FETCH*type*ATTRIBUTES\" call in\nits return list, as described in \"Package-specific Attribute Handling\" below. Otherwise,\nonly built-in attributes will be returned.\n\nreftype\nThis routine expects a single parameter--a reference to a subroutine or variable. It returns\nthe built-in type of the referenced variable, ignoring any package into which it might have\nbeen blessed. This can be useful for determining the *type* value which forms part of the\nmethod names described in \"Package-specific Attribute Handling\" below.\n\nNote that these routines are *not* exported by default.\n"
                },
                {
                    "name": "Package-specific Attribute Handling",
                    "content": "WARNING: the mechanisms described here are still experimental. Do not rely on the current\nimplementation. In particular, there is no provision for applying package attributes to 'cloned'\ncopies of subroutines used as closures. (See \"Making References\" in perlref for information on\nclosures.) Package-specific attribute handling may change incompatibly in a future release.\n\nWhen an attribute list is present in a declaration, a check is made to see whether an attribute\n'modify' handler is present in the appropriate package (or its @ISA inheritance tree).\nSimilarly, when \"attributes::get\" is called on a valid reference, a check is made for an\nappropriate attribute 'fetch' handler. See \"EXAMPLES\" to see how the \"appropriate package\"\ndetermination works.\n\nThe handler names are based on the underlying type of the variable being declared or of the\nreference passed. Because these attributes are associated with subroutine or variable\ndeclarations, this deliberately ignores any possibility of being blessed into some package.\nThus, a subroutine declaration uses \"CODE\" as its *type*, and even a blessed hash reference uses\n\"HASH\" as its *type*.\n\nThe class methods invoked for modifying and fetching are these:\n\nFETCH*type*ATTRIBUTES\nThis method is called with two arguments: the relevant package name, and a reference to a\nvariable or subroutine for which package-defined attributes are desired. The expected return\nvalue is a list of associated attributes. This list may be empty.\n\nMODIFY*type*ATTRIBUTES\nThis method is called with two fixed arguments, followed by the list of attributes from the\nrelevant declaration. The two fixed arguments are the relevant package name and a reference\nto the declared subroutine or variable. The expected return value is a list of attributes\nwhich were not recognized by this handler. Note that this allows for a derived class to\ndelegate a call to its base class, and then only examine the attributes which the base class\ndidn't already handle for it.\n\nThe call to this method is currently made *during* the processing of the declaration. In\nparticular, this means that a subroutine reference will probably be for an undefined\nsubroutine, even if this declaration is actually part of the definition.\n\nCalling \"attributes::get()\" from within the scope of a null package declaration \"package ;\" for\nan unblessed variable reference will not provide any starting package name for the 'fetch'\nmethod lookup. Thus, this circumstance will not result in a method call for package-defined\nattributes. A named subroutine knows to which symbol table entry it belongs (or originally\nbelonged), and it will use the corresponding package. An anonymous subroutine knows the package\nname into which it was compiled (unless it was also compiled with a null package declaration),\nand so it will use that package name.\n"
                },
                {
                    "name": "Syntax of Attribute Lists",
                    "content": "An attribute list is a sequence of attribute specifications, separated by whitespace or a colon\n(with optional whitespace). Each attribute specification is a simple name, optionally followed\nby a parenthesised parameter list. If such a parameter list is present, it is scanned past as\nfor the rules for the \"q()\" operator. (See \"Quote and Quote-like Operators\" in perlop.) The\nparameter list is passed as it was found, however, and not as per \"q()\".\n\nSome examples of syntactically valid attribute lists:\n\nswitch(10,foo(7,3))  :  expensive\nUgly('\\(\") :Bad\n5x5\nlvalue method\n\nSome examples of syntactically invalid attribute lists (with annotation):\n\nswitch(10,foo()             # ()-string not balanced\nUgly('(')                   # ()-string not balanced\n5x5                         # \"5x5\" not a valid identifier\nY2::north                   # \"Y2::north\" not a simple identifier\nfoo + bar                   # \"+\" neither a colon nor whitespace\n"
                }
            ]
        },
        "EXPORTS": {
            "content": "",
            "subsections": [
                {
                    "name": "Default exports",
                    "content": "None.\n"
                },
                {
                    "name": "Available exports",
                    "content": "The routines \"get\" and \"reftype\" are exportable.\n"
                },
                {
                    "name": "Export tags defined",
                    "content": "The \":ALL\" tag will get all of the above exports.\n"
                }
            ]
        },
        "EXAMPLES": {
            "content": "Here are some samples of syntactically valid declarations, with annotation as to how they\nresolve internally into \"use attributes\" invocations by perl. These examples are primarily\nuseful to see how the \"appropriate package\" is found for the possible method lookups for\npackage-defined attributes.\n\n1.  Code:\n\npackage Canine;\npackage Dog;\nmy Canine $spot : Watchful ;\n\nEffect:\n\nuse attributes ();\nattributes::->import(Canine => \\$spot, \"Watchful\");\n\n2.  Code:\n\npackage Felis;\nmy $cat : Nervous;\n\nEffect:\n\nuse attributes ();\nattributes::->import(Felis => \\$cat, \"Nervous\");\n\n3.  Code:\n\npackage X;\nsub foo : lvalue ;\n\nEffect:\n\nuse attributes X => \\&foo, \"lvalue\";\n\n4.  Code:\n\npackage X;\nsub Y::x : lvalue { 1 }\n\nEffect:\n\nuse attributes Y => \\&Y::x, \"lvalue\";\n\n5.  Code:\n\npackage X;\nsub foo { 1 }\n\npackage Y;\nBEGIN { *bar = \\&X::foo; }\n\npackage Z;\nsub Y::bar : lvalue ;\n\nEffect:\n\nuse attributes X => \\&X::foo, \"lvalue\";\n\nThis last example is purely for purposes of completeness. You should not be trying to mess with\nthe attributes of something in a package that's not your own.\n",
            "subsections": []
        },
        "MORE EXAMPLES": {
            "content": "1.\nsub MODIFYCODEATTRIBUTES {\nmy ($class,$code,@attrs) = @;\n\nmy $allowed = 'MyAttribute';\nmy @bad = grep { $ ne $allowed } @attrs;\n\nreturn @bad;\n}\n\nsub foo : MyAttribute {\nprint \"foo\\n\";\n}\n\nThis example runs. At compile time \"MODIFYCODEATTRIBUTES\" is called. In that subroutine,\nwe check if any attribute is disallowed and we return a list of these \"bad attributes\".\n\nAs we return an empty list, everything is fine.\n\n2.\nsub MODIFYCODEATTRIBUTES {\nmy ($class,$code,@attrs) = @;\n\nmy $allowed = 'MyAttribute';\nmy @bad = grep{ $ ne $allowed }@attrs;\n\nreturn @bad;\n}\n\nsub foo : MyAttribute Test {\nprint \"foo\\n\";\n}\n\nThis example is aborted at compile time as we use the attribute \"Test\" which isn't allowed.\n\"MODIFYCODEATTRIBUTES\" returns a list that contains a single element ('Test').\n",
            "subsections": []
        },
        "SEE ALSO": {
            "content": "\"Private Variables via my()\" in perlsub and \"Subroutine Attributes\" in perlsub for details on\nthe basic declarations; \"use\" in perlfunc for details on the normal invocation mechanism.\n",
            "subsections": []
        }
    },
    "summary": "attributes - get/set subroutine or variable attributes",
    "flags": [],
    "examples": [
        "Here are some samples of syntactically valid declarations, with annotation as to how they",
        "resolve internally into \"use attributes\" invocations by perl. These examples are primarily",
        "useful to see how the \"appropriate package\" is found for the possible method lookups for",
        "package-defined attributes.",
        "1.  Code:",
        "package Canine;",
        "package Dog;",
        "my Canine $spot : Watchful ;",
        "Effect:",
        "use attributes ();",
        "attributes::->import(Canine => \\$spot, \"Watchful\");",
        "2.  Code:",
        "package Felis;",
        "my $cat : Nervous;",
        "Effect:",
        "use attributes ();",
        "attributes::->import(Felis => \\$cat, \"Nervous\");",
        "3.  Code:",
        "package X;",
        "sub foo : lvalue ;",
        "Effect:",
        "use attributes X => \\&foo, \"lvalue\";",
        "4.  Code:",
        "package X;",
        "sub Y::x : lvalue { 1 }",
        "Effect:",
        "use attributes Y => \\&Y::x, \"lvalue\";",
        "5.  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."
    ],
    "see_also": []
}