A little known built-in Perl feature is attributes. However, the official documentation is doing a rather bad job introducing newbies to the concept. At the same time, frameworks like Catalyst use attributes extensively which seems to make many things easier there. Since using something without knowing the implications sucks a bit, I’d like to know the details. Syntax-wise they look like Python’s decorators, but the documentation implies something simpler.
Could you explain (with real-world examples if possible) what attributes are good for and what happens behind the doors?
You are right, the documentation is not very clear in this area, especially since attributes are not so complicated. If you define a subroutine attribute, like this:
Perl will while compiling your program (this is important) look for the magic sub
MODIFY_CODE_ATTRIBUTESin the current package or any of its parent classes. This will be called with the name of the current package, a reference to your subroutine, and a list of the attributes defined for this subroutine. If this handler does not exist, compilation will fail.What you do in this handler is entirely up to you. Yes, that’s right. No hidden magic whatsoever. If you want to signal an error, returning the name of the offending attributes will cause the compilation to fail with an "invalid attribute" message.
There is another handler called
FETCH_CODE_ATTRIBUTESthat will be called whenever someone saysThis handler gets passed the package name and subroutine reference, and is supposed to return a list of the subroutine’s attributes (though what you really do is again up to you).
Here is an example to enable simple "tagging" of methods with arbitrary attributes, which you can query later:
Now, in MyClass and all its subclasses, you can use arbitrary attributes, and query them using
attributes::get():In summary, attributes don’t do very much which on the other hand makes them very flexible: You can use them as real "attributes" (as shown in this example), implement something like decorators (see Mike Friedman’s article), or for your own devious purposes.