📜 ⬆️ ⬇️

Attributes: Introduction

Attributes appeared in Perl for quite some time. The landmark version for old-timers Perl 5.005 contained the pretty useless pragma attrs . This pragma made it possible to hang a pair of built-in attributes on the function, for which it was necessary to specify use attrs with the appropriate parameters inside this function. True, in March 2000 in Perl 5.6 this pragma was declared deprecated. It was replaced by the attributes module, as well as an extended syntax for declaring variables / functions. It became possible to create their own labels for them and enter handlers for these labels. For unknown reasons, the popularity of the attributes did not receive. It's a pity.

Closer to the point


Now they probably would have been called not attributes, but tags. Everything looks simple - you can add several labels to the declared variable or function. There are several standard Perl attributes, but you can enter your own. The built-in attributes are written in lower case letters, and therefore it is not recommended to use such a register for custom tags - in order to avoid overlays in the future and versions in the present.

Attribute syntax is fairly straightforward:

my $myVar : myAttribute = 10;
sub mySub : myAttribute1 : myAttribute2 {:}


The interpreter does not impose restrictions on the presence of a space between the colon and the name of the attribute; it personally seems more visible to me when they are written together.
')
Attributes can be hung on functions and on variables - scalars, hashes, arrays.

What is it for


For examples to go close - a group of modules united under the name Attribute::Util . Lives on CPAN. I will not comment on the possibility of their use in real projects, but as a simple and graphic illustration it is what you need.

The first one, Attribute::Abstract , offers a substitute for the classic description of abstract methods. Pay attention to it if you have similar ads:

sub myMethod { die "Abstract method called!"; }

The syntax suggested by him is much clearer:

sub myMethod: Abstract;

The second class, Attribute::Memoize , allows you to add caching to functions that return a constant result for the same sets of arguments. Of course, it’s not difficult to wrap the function code in the if block, but again, you can simply mark the function with an attribute :Memoize and know that its result is cached.

The third class, Attribute::Method , allows you to get rid of writing the first line of almost any method:

my $self = shift;

Just set the attribute to the method :Method , and $self appears by itself. In addition, you can specify which arguments are passed to the method - then they will also be initialized:

sub myMethod :Method($x) { print "self=$self, x=$x\n" }

Interesting? Then do not forget to look into the source code of the modules.

UPD : article continuation: Attributes: a look inside

Source: https://habr.com/ru/post/53451/


All Articles