in reply to Where subroutine attributes will be used?

As far as I know, there are basically three ways to define and use subroutine attributes in the Perl environment:

The built-in attributes are integrated into the compilation process and can affect what counts as legal syntax (e.g. lvalue). In addition to the two built-in attributes listed above, there are two version specific subroutine attributes that you might see in older code:

As there are very few built-in attributes, Perl and its extensions provide two mechanisms for custom attribute definitions. Common reasons to use custom attributes are

  1. generation of a wrapper function that inserts code before and after the subroutine call. The code assigned to the subroutine name is replaced by the code making before+call+after code. For example, you might want to log the input parameters and return values of a call.
  2. generation supplemental functions and data based on the actual attributes.
  3. compilation messages and metadata statistics for use by frameworks (e.g. Catalyst and MooseClass::Std).

Custom attributes defined using FETCH_CODE_ATTRIBUTES and MODIFY_CODE_ATTRIBUTES can be used safely under mod_perl but only handle use cases 2 and 3 above. They can't be used to generate wrappers that replace subroutine definitions (use case 1) because MODIFY_CODE_ATTRIBUTES is called before the function body has been defined and inserted into the symbol table.

Attribute::Handlers can be used for all three purposes, but it relies on the CHECK and INIT phases for loading up a module and these don't get triggered under mod_perl or in other environments that rely on eval to load code. The issues related to the two different methods for defining custom attributes has been discussed at length in the following threads:

For examples using customized attributes, see the following links:

Best, beth

Replies are listed 'Best First'.
Re^2: Where subroutine attributes will be used?
by stvn (Monsignor) on Mar 09, 2009 at 17:49 UTC
    ... compilation messages and metadata statistics for use by frameworks (e.g. Catalyst and Moose).

    Actually, Moose does not and never will use attributes. As perrin says below, they are best avoided at all costs. The API to use them is horrid and the limitations of that API are (IMO at least) totally unacceptable. Even Catalyst will eventually do away with attributes in favor of using something similar to how Moose works or something more radical like Devel::Declare.

    -stvn