Subroutine Attributes

A subroutine declaration or definition may have a list of attributes associated with it. If such an attribute list is present, it is broken up at whitespace or colon boundaries and treated as though a use attributes had been seen. See the use attributes pragma in Glossary for internal details. There are three standard attributes for subroutines: locked, method, and lvalue.

The locked and method Attributes

# Only one thread is allowed into this function.
sub afunc : locked { … }

# Only one thread is allowed into this function on a given object.
sub afunc : locked method { … }

Setting the locked attribute is meaningful only when the subroutine or method is intended to be called by multiple threads simultaneously. When set on a nonmethod subroutine, Perl ensures that a lock is acquired on the subroutine itself before that subroutine is entered. When set on a method subroutine (that is, one also marked with the method attribute), Perl ensures that any invocation of it implicitly locks its first argument (the object) before execution.

Semantics of this lock are the same as using the lock operator on the subroutine as the first statement in that routine. See Chapter 17, for more on locking.

The method attribute can be used by itself:

sub afunc : method { … }

Currently this has only the effect of marking the subroutine so as not to trigger the "Ambiguous call resolved as CORE::%s" warning. (We may make it mean more someday.)

The attribute system is user-extensible, ...

Get Programming Perl, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.