1attributes(3pm)        Perl Programmers Reference Guide        attributes(3pm)
2
3
4

NAME

6       attributes - get/set subroutine or variable attributes
7

SYNOPSIS

9         sub foo : method ;
10         my ($x,@y,%z) : Bent = 1;
11         my $s = sub : method { ... };
12
13         use attributes ();    # optional, to get subroutine declarations
14         my @attrlist = attributes::get(\&foo);
15
16         use attributes 'get'; # import the attributes::get subroutine
17         my @attrlist = get \&foo;
18

DESCRIPTION

20       Subroutine declarations and definitions may optionally have attribute
21       lists associated with them.  (Variable "my" declarations also may, but
22       see the warning below.)  Perl handles these declarations by passing
23       some information about the call site and the thing being declared along
24       with the attribute list to this module.  In particular, the first
25       example above is equivalent to the following:
26
27           use attributes __PACKAGE__, \&foo, 'method';
28
29       The second example in the synopsis does something equivalent to this:
30
31           use attributes ();
32           my ($x,@y,%z);
33           attributes::->import(__PACKAGE__, \$x, 'Bent');
34           attributes::->import(__PACKAGE__, \@y, 'Bent');
35           attributes::->import(__PACKAGE__, \%z, 'Bent');
36           ($x,@y,%z) = 1;
37
38       Yes, that's a lot of expansion.
39
40       WARNING: attribute declarations for variables are still evolving.  The
41       semantics and interfaces of such declarations could change in future
42       versions.  They are present for purposes of experimentation with what
43       the semantics ought to be.  Do not rely on the current implementation
44       of this feature.
45
46       There are only a few attributes currently handled by Perl itself (or
47       directly by this module, depending on how you look at it.)  However,
48       package-specific attributes are allowed by an extension mechanism.
49       (See "Package-specific Attribute Handling" below.)
50
51       The setting of subroutine attributes happens at compile time.  Variable
52       attributes in "our" declarations are also applied at compile time.
53       However, "my" variables get their attributes applied at run-time.  This
54       means that you have to reach the run-time component of the "my" before
55       those attributes will get applied.  For example:
56
57           my $x : Bent = 42 if 0;
58
59       will neither assign 42 to $x nor will it apply the "Bent" attribute to
60       the variable.
61
62       An attempt to set an unrecognized attribute is a fatal error.  (The
63       error is trappable, but it still stops the compilation within that
64       "eval".)  Setting an attribute with a name that's all lowercase letters
65       that's not a built-in attribute (such as "foo") will result in a
66       warning with -w or "use warnings 'reserved'".
67
68   What "import" does
69       In the description it is mentioned that
70
71         sub foo : method;
72
73       is equivalent to
74
75         use attributes __PACKAGE__, \&foo, 'method';
76
77       As you might know this calls the "import" function of "attributes" at
78       compile time with these parameters: 'attributes', the caller's package
79       name, the reference to the code and 'method'.
80
81         attributes->import( __PACKAGE__, \&foo, 'method' );
82
83       So you want to know what "import" actually does?
84
85       First of all "import" gets the type of the third parameter ('CODE' in
86       this case).  "attributes.pm" checks if there is a subroutine called
87       "MODIFY_<reftype>_ATTRIBUTES" in the caller's namespace (here: 'main').
88       In this case a subroutine "MODIFY_CODE_ATTRIBUTES" is required.  Then
89       this method is called to check if you have used a "bad attribute".  The
90       subroutine call in this example would look like
91
92         MODIFY_CODE_ATTRIBUTES( 'main', \&foo, 'method' );
93
94       "MODIFY_<reftype>_ATTRIBUTES" has to return a list of all "bad
95       attributes".  If there are any bad attributes "import" croaks.
96
97       (See "Package-specific Attribute Handling" below.)
98
99   Built-in Attributes
100       The following are the built-in attributes for subroutines:
101
102       lvalue
103           Indicates that the referenced subroutine is a valid lvalue and can
104           be assigned to.  The subroutine must return a modifiable value such
105           as a scalar variable, as described in perlsub.
106
107           This module allows one to set this attribute on a subroutine that
108           is already defined.  For Perl subroutines (XSUBs are fine), it may
109           or may not do what you want, depending on the code inside the
110           subroutine, with details subject to change in future Perl versions.
111           You may run into problems with lvalue context not being propagated
112           properly into the subroutine, or maybe even assertion failures.
113           For this reason, a warning is emitted if warnings are enabled.  In
114           other words, you should only do this if you really know what you
115           are doing.  You have been warned.
116
117       method
118           Indicates that the referenced subroutine is a method.  A subroutine
119           so marked will not trigger the "Ambiguous call resolved as
120           CORE::%s" warning.
121
122       prototype(..)
123           The "prototype" attribute is an alternate means of specifying a
124           prototype on a sub.  The desired prototype is within the parens.
125
126           The prototype from the attribute is assigned to the sub immediately
127           after the prototype from the sub, which means that if both are
128           declared at the same time, the traditionally defined prototype is
129           ignored.  In other words, "sub foo($$) : prototype(@) {}" is
130           indistinguishable from "sub foo(@){}".
131
132           If illegalproto warnings are enabled, the prototype declared inside
133           this attribute will be sanity checked at compile time.
134
135       const
136           This experimental attribute, introduced in Perl 5.22, only applies
137           to anonymous subroutines.  It causes the subroutine to be called as
138           soon as the "sub" expression is evaluated.  The return value is
139           captured and turned into a constant subroutine.
140
141       The following are the built-in attributes for variables:
142
143       shared
144           Indicates that the referenced variable can be shared across
145           different threads when used in conjunction with the threads and
146           threads::shared modules.
147
148   Available Subroutines
149       The following subroutines are available for general use once this
150       module has been loaded:
151
152       get This routine expects a single parameter--a reference to a
153           subroutine or variable.  It returns a list of attributes, which may
154           be empty.  If passed invalid arguments, it uses die() (via
155           Carp::croak) to raise a fatal exception.  If it can find an
156           appropriate package name for a class method lookup, it will include
157           the results from a "FETCH_type_ATTRIBUTES" call in its return list,
158           as described in "Package-specific Attribute Handling" below.
159           Otherwise, only built-in attributes will be returned.
160
161       reftype
162           This routine expects a single parameter--a reference to a
163           subroutine or variable.  It returns the built-in type of the
164           referenced variable, ignoring any package into which it might have
165           been blessed.  This can be useful for determining the type value
166           which forms part of the method names described in "Package-specific
167           Attribute Handling" below.
168
169       Note that these routines are not exported by default.
170
171   Package-specific Attribute Handling
172       WARNING: the mechanisms described here are still experimental.  Do not
173       rely on the current implementation.  In particular, there is no
174       provision for applying package attributes to 'cloned' copies of
175       subroutines used as closures.  (See "Making References" in perlref for
176       information on closures.)  Package-specific attribute handling may
177       change incompatibly in a future release.
178
179       When an attribute list is present in a declaration, a check is made to
180       see whether an attribute 'modify' handler is present in the appropriate
181       package (or its @ISA inheritance tree).  Similarly, when
182       "attributes::get" is called on a valid reference, a check is made for
183       an appropriate attribute 'fetch' handler.  See "EXAMPLES" to see how
184       the "appropriate package" determination works.
185
186       The handler names are based on the underlying type of the variable
187       being declared or of the reference passed.  Because these attributes
188       are associated with subroutine or variable declarations, this
189       deliberately ignores any possibility of being blessed into some
190       package.  Thus, a subroutine declaration uses "CODE" as its type, and
191       even a blessed hash reference uses "HASH" as its type.
192
193       The class methods invoked for modifying and fetching are these:
194
195       FETCH_type_ATTRIBUTES
196           This method is called with two arguments:  the relevant package
197           name, and a reference to a variable or subroutine for which
198           package-defined attributes are desired.  The expected return value
199           is a list of associated attributes.  This list may be empty.
200
201       MODIFY_type_ATTRIBUTES
202           This method is called with two fixed arguments, followed by the
203           list of attributes from the relevant declaration.  The two fixed
204           arguments are the relevant package name and a reference to the
205           declared subroutine or variable.  The expected return value is a
206           list of attributes which were not recognized by this handler.  Note
207           that this allows for a derived class to delegate a call to its base
208           class, and then only examine the attributes which the base class
209           didn't already handle for it.
210
211           The call to this method is currently made during the processing of
212           the declaration.  In particular, this means that a subroutine
213           reference will probably be for an undefined subroutine, even if
214           this declaration is actually part of the definition.
215
216       Calling "attributes::get()" from within the scope of a null package
217       declaration "package ;" for an unblessed variable reference will not
218       provide any starting package name for the 'fetch' method lookup.  Thus,
219       this circumstance will not result in a method call for package-defined
220       attributes.  A named subroutine knows to which symbol table entry it
221       belongs (or originally belonged), and it will use the corresponding
222       package.  An anonymous subroutine knows the package name into which it
223       was compiled (unless it was also compiled with a null package
224       declaration), and so it will use that package name.
225
226   Syntax of Attribute Lists
227       An attribute list is a sequence of attribute specifications, separated
228       by whitespace or a colon (with optional whitespace).  Each attribute
229       specification is a simple name, optionally followed by a parenthesised
230       parameter list.  If such a parameter list is present, it is scanned
231       past as for the rules for the "q()" operator.  (See "Quote and Quote-
232       like Operators" in perlop.)  The parameter list is passed as it was
233       found, however, and not as per "q()".
234
235       Some examples of syntactically valid attribute lists:
236
237           switch(10,foo(7,3))  :  expensive
238           Ugly('\(") :Bad
239           _5x5
240           lvalue method
241
242       Some examples of syntactically invalid attribute lists (with
243       annotation):
244
245           switch(10,foo()             # ()-string not balanced
246           Ugly('(')                   # ()-string not balanced
247           5x5                         # "5x5" not a valid identifier
248           Y2::north                   # "Y2::north" not a simple identifier
249           foo + bar                   # "+" neither a colon nor whitespace
250

EXPORTS

252   Default exports
253       None.
254
255   Available exports
256       The routines "get" and "reftype" are exportable.
257
258   Export tags defined
259       The ":ALL" tag will get all of the above exports.
260

EXAMPLES

262       Here are some samples of syntactically valid declarations, with
263       annotation as to how they resolve internally into "use attributes"
264       invocations by perl.  These examples are primarily useful to see how
265       the "appropriate package" is found for the possible method lookups for
266       package-defined attributes.
267
268       1.  Code:
269
270               package Canine;
271               package Dog;
272               my Canine $spot : Watchful ;
273
274           Effect:
275
276               use attributes ();
277               attributes::->import(Canine => \$spot, "Watchful");
278
279       2.  Code:
280
281               package Felis;
282               my $cat : Nervous;
283
284           Effect:
285
286               use attributes ();
287               attributes::->import(Felis => \$cat, "Nervous");
288
289       3.  Code:
290
291               package X;
292               sub foo : lvalue ;
293
294           Effect:
295
296               use attributes X => \&foo, "lvalue";
297
298       4.  Code:
299
300               package X;
301               sub Y::x : lvalue { 1 }
302
303           Effect:
304
305               use attributes Y => \&Y::x, "lvalue";
306
307       5.  Code:
308
309               package X;
310               sub foo { 1 }
311
312               package Y;
313               BEGIN { *bar = \&X::foo; }
314
315               package Z;
316               sub Y::bar : lvalue ;
317
318           Effect:
319
320               use attributes X => \&X::foo, "lvalue";
321
322       This last example is purely for purposes of completeness.  You should
323       not be trying to mess with the attributes of something in a package
324       that's not your own.
325

MORE EXAMPLES

327       1.
328               sub MODIFY_CODE_ATTRIBUTES {
329                  my ($class,$code,@attrs) = @_;
330
331                  my $allowed = 'MyAttribute';
332                  my @bad = grep { $_ ne $allowed } @attrs;
333
334                  return @bad;
335               }
336
337               sub foo : MyAttribute {
338                  print "foo\n";
339               }
340
341           This example runs.  At compile time "MODIFY_CODE_ATTRIBUTES" is
342           called.  In that subroutine, we check if any attribute is
343           disallowed and we return a list of these "bad attributes".
344
345           As we return an empty list, everything is fine.
346
347       2.
348             sub MODIFY_CODE_ATTRIBUTES {
349                my ($class,$code,@attrs) = @_;
350
351                my $allowed = 'MyAttribute';
352                my @bad = grep{ $_ ne $allowed }@attrs;
353
354                return @bad;
355             }
356
357             sub foo : MyAttribute Test {
358                print "foo\n";
359             }
360
361           This example is aborted at compile time as we use the attribute
362           "Test" which isn't allowed.  "MODIFY_CODE_ATTRIBUTES" returns a
363           list that contains a single element ('Test').
364

SEE ALSO

366       "Private Variables via my()" in perlsub and "Subroutine Attributes" in
367       perlsub for details on the basic declarations; "use" in perlfunc for
368       details on the normal invocation mechanism.
369
370
371
372perl v5.30.2                      2020-03-27                   attributes(3pm)
Impressum