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       locked
136           The "locked" attribute is deprecated, and has no effect in 5.10.0
137           and later.  It was used as part of the now-removed "Perl 5.005
138           threads". It will disappear in Perl 5.28, after which its use will
139           be fatal.
140
141       const
142           This experimental attribute, introduced in Perl 5.22, only applies
143           to anonymous subroutines.  It causes the subroutine to be called as
144           soon as the "sub" expression is evaluated.  The return value is
145           captured and turned into a constant subroutine.
146
147       The following are the built-in attributes for variables:
148
149       shared
150           Indicates that the referenced variable can be shared across
151           different threads when used in conjunction with the threads and
152           threads::shared modules.
153
154       unique
155           The "unique" attribute is deprecated, and has no effect in 5.10.0
156           and later.  It used to indicate that a single copy of an "our"
157           variable was to be used by all interpreters should the program
158           happen to be running in a multi-interpreter environment. It will
159           disappear in 5.28, after which its use will be fatal.
160
161   Available Subroutines
162       The following subroutines are available for general use once this
163       module has been loaded:
164
165       get This routine expects a single parameter--a reference to a
166           subroutine or variable.  It returns a list of attributes, which may
167           be empty.  If passed invalid arguments, it uses die() (via
168           Carp::croak) to raise a fatal exception.  If it can find an
169           appropriate package name for a class method lookup, it will include
170           the results from a "FETCH_type_ATTRIBUTES" call in its return list,
171           as described in "Package-specific Attribute Handling" below.
172           Otherwise, only built-in attributes will be returned.
173
174       reftype
175           This routine expects a single parameter--a reference to a
176           subroutine or variable.  It returns the built-in type of the
177           referenced variable, ignoring any package into which it might have
178           been blessed.  This can be useful for determining the type value
179           which forms part of the method names described in "Package-specific
180           Attribute Handling" below.
181
182       Note that these routines are not exported by default.
183
184   Package-specific Attribute Handling
185       WARNING: the mechanisms described here are still experimental.  Do not
186       rely on the current implementation.  In particular, there is no
187       provision for applying package attributes to 'cloned' copies of
188       subroutines used as closures.  (See "Making References" in perlref for
189       information on closures.)  Package-specific attribute handling may
190       change incompatibly in a future release.
191
192       When an attribute list is present in a declaration, a check is made to
193       see whether an attribute 'modify' handler is present in the appropriate
194       package (or its @ISA inheritance tree).  Similarly, when
195       "attributes::get" is called on a valid reference, a check is made for
196       an appropriate attribute 'fetch' handler.  See "EXAMPLES" to see how
197       the "appropriate package" determination works.
198
199       The handler names are based on the underlying type of the variable
200       being declared or of the reference passed.  Because these attributes
201       are associated with subroutine or variable declarations, this
202       deliberately ignores any possibility of being blessed into some
203       package.  Thus, a subroutine declaration uses "CODE" as its type, and
204       even a blessed hash reference uses "HASH" as its type.
205
206       The class methods invoked for modifying and fetching are these:
207
208       FETCH_type_ATTRIBUTES
209           This method is called with two arguments:  the relevant package
210           name, and a reference to a variable or subroutine for which
211           package-defined attributes are desired.  The expected return value
212           is a list of associated attributes.  This list may be empty.
213
214       MODIFY_type_ATTRIBUTES
215           This method is called with two fixed arguments, followed by the
216           list of attributes from the relevant declaration.  The two fixed
217           arguments are the relevant package name and a reference to the
218           declared subroutine or variable.  The expected return value is a
219           list of attributes which were not recognized by this handler.  Note
220           that this allows for a derived class to delegate a call to its base
221           class, and then only examine the attributes which the base class
222           didn't already handle for it.
223
224           The call to this method is currently made during the processing of
225           the declaration.  In particular, this means that a subroutine
226           reference will probably be for an undefined subroutine, even if
227           this declaration is actually part of the definition.
228
229       Calling "attributes::get()" from within the scope of a null package
230       declaration "package ;" for an unblessed variable reference will not
231       provide any starting package name for the 'fetch' method lookup.  Thus,
232       this circumstance will not result in a method call for package-defined
233       attributes.  A named subroutine knows to which symbol table entry it
234       belongs (or originally belonged), and it will use the corresponding
235       package.  An anonymous subroutine knows the package name into which it
236       was compiled (unless it was also compiled with a null package
237       declaration), and so it will use that package name.
238
239   Syntax of Attribute Lists
240       An attribute list is a sequence of attribute specifications, separated
241       by whitespace or a colon (with optional whitespace).  Each attribute
242       specification is a simple name, optionally followed by a parenthesised
243       parameter list.  If such a parameter list is present, it is scanned
244       past as for the rules for the "q()" operator.  (See "Quote and Quote-
245       like Operators" in perlop.)  The parameter list is passed as it was
246       found, however, and not as per "q()".
247
248       Some examples of syntactically valid attribute lists:
249
250           switch(10,foo(7,3))  :  expensive
251           Ugly('\(") :Bad
252           _5x5
253           lvalue method
254
255       Some examples of syntactically invalid attribute lists (with
256       annotation):
257
258           switch(10,foo()             # ()-string not balanced
259           Ugly('(')                   # ()-string not balanced
260           5x5                         # "5x5" not a valid identifier
261           Y2::north                   # "Y2::north" not a simple identifier
262           foo + bar                   # "+" neither a colon nor whitespace
263

EXPORTS

265   Default exports
266       None.
267
268   Available exports
269       The routines "get" and "reftype" are exportable.
270
271   Export tags defined
272       The ":ALL" tag will get all of the above exports.
273

EXAMPLES

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

MORE EXAMPLES

340       1.
341               sub MODIFY_CODE_ATTRIBUTES {
342                  my ($class,$code,@attrs) = @_;
343
344                  my $allowed = 'MyAttribute';
345                  my @bad = grep { $_ ne $allowed } @attrs;
346
347                  return @bad;
348               }
349
350               sub foo : MyAttribute {
351                  print "foo\n";
352               }
353
354           This example runs.  At compile time "MODIFY_CODE_ATTRIBUTES" is
355           called.  In that subroutine, we check if any attribute is
356           disallowed and we return a list of these "bad attributes".
357
358           As we return an empty list, everything is fine.
359
360       2.
361             sub MODIFY_CODE_ATTRIBUTES {
362                my ($class,$code,@attrs) = @_;
363
364                my $allowed = 'MyAttribute';
365                my @bad = grep{ $_ ne $allowed }@attrs;
366
367                return @bad;
368             }
369
370             sub foo : MyAttribute Test {
371                print "foo\n";
372             }
373
374           This example is aborted at compile time as we use the attribute
375           "Test" which isn't allowed.  "MODIFY_CODE_ATTRIBUTES" returns a
376           list that contains a single element ('Test').
377

SEE ALSO

379       "Private Variables via my()" in perlsub and "Subroutine Attributes" in
380       perlsub for details on the basic declarations; "use" in perlfunc for
381       details on the normal invocation mechanism.
382
383
384
385perl v5.26.3                      2018-03-23                   attributes(3pm)
Impressum