Cari di Perl 
    Perl User Manual
Daftar Isi
(Sebelumnya) Return elapsed time for self a ...Replace functions with ones th ... (Berikutnya)
Pragmas

Get/set subroutine or variable attributes

Daftar Isi

NAME

attributes - get/set subroutine or variable attributes

SYNOPSIS

  1. sub foo : method ;
  2. my ($x,@y,%z) : Bent = 1;
  3. my $s = sub : method { ... };
  4. use attributes ();# optional, to get subroutine declarations
  5. my @attrlist = attributes::get(\&foo);
  6. use attributes 'get'; # import the attributes::get subroutine
  7. my @attrlist = get \&foo;

DESCRIPTION

Subroutine declarations and definitions may optionally have attribute listsassociated with them. (Variable my declarations also may, but see thewarning below.) Perl handles these declarations by passing some informationabout the call site and the thing being declared along with the attributelist to this module. In particular, the first example above is equivalent tothe following:

  1. use attributes __PACKAGE__, \&foo, 'method';

The second example in the synopsis does something equivalent to this:

  1. use attributes ();
  2. my ($x,@y,%z);
  3. attributes::->import(__PACKAGE__, \$x, 'Bent');
  4. attributes::->import(__PACKAGE__, \@y, 'Bent');
  5. attributes::->import(__PACKAGE__, \%z, 'Bent');
  6. ($x,@y,%z) = 1;

Yes, that's a lot of expansion.

WARNING: attribute declarations for variables are still evolving.The semantics and interfaces of such declarations could change infuture versions. They are present for purposes of experimentationwith what the semantics ought to be. Do not rely on the currentimplementation of this feature.

There are only a few attributes currently handled by Perl itself (ordirectly by this module, depending on how you look at it.) However,package-specific attributes are allowed by an extension mechanism.(See Package-specific Attribute Handling below.)

The setting of subroutine attributes happens at compile time.Variable attributes in our declarations are also applied at compile time.However, my variables get their attributes applied at run-time.This means that you have to reach the run-time component of the mybefore those attributes will get applied. For example:

  1. my $x : Bent = 42 if 0;

will neither assign 42 to $x nor will it apply the Bent attributeto the variable.

An attempt to set an unrecognized attribute is a fatal error. (Theerror is trappable, but it still stops the compilation within thateval.) Setting an attribute with a name that's all lowercaseletters that's not a built-in attribute (such as "foo") will result ina warning with -w or use warnings 'reserved'.

What import does

In the description it is mentioned that

  1. sub foo : method;

is equivalent to

  1. use attributes __PACKAGE__, \&foo, 'method';

As you might know this calls the import function of attributes at compile time with these parameters: 'attributes', the caller's package name, the reference to the code and 'method'.

  1. attributes->import( __PACKAGE__, \&foo, 'method' );

So you want to know what import actually does?

First of all import gets the type of the third parameter ('CODE' in this case).attributes.pm checks if there is a subroutine called MODIFY_<reftype>_ATTRIBUTESin the caller's namespace (here: 'main'). In this case asubroutine MODIFY_CODE_ATTRIBUTES is required. Then thismethod is called to check if you have used a "bad attribute".The subroutine call in this example would look like

  1. MODIFY_CODE_ATTRIBUTES( 'main', \&foo, 'method' );

MODIFY_<reftype>_ATTRIBUTES has to return a list of all "bad attributes".If there are any bad attributes import croaks.

(See Package-specific Attribute Handling below.)

Built-in Attributes

The following are the built-in attributes for subroutines:

  • lvalue

    Indicates that the referenced subroutine is a valid lvalue and canbe assigned to. The subroutine must return a modifiable value suchas a scalar variable, as described in perlsub.

    This module allows one to set this attribute on a subroutine that isalready defined. For Perl subroutines (XSUBs are fine), it may or may notdo what you want, depending on the code inside the subroutine, with detailssubject to change in future Perl versions. You may run into problems withlvalue context not being propagated properly into the subroutine, or maybeeven assertion failures. For this reason, a warning is emitted if warningsare enabled. In other words, you should only do this if you really knowwhat you are doing. You have been warned.

  • method

    Indicates that the referenced subroutineis a method. A subroutine so markedwill not trigger the "Ambiguous call resolved as CORE::%s" warning.

  • locked

    The "locked" attribute has no effect in5.10.0 and later. It was used as partof the now-removed "Perl 5.005 threads".

Available Subroutines

The following subroutines are available for general use once this modulehas been loaded:

  • get

    This routine expects a single parameter--a reference to asubroutine or variable. It returns a list of attributes, which may beempty. If passed invalid arguments, it uses die() (via Carp::croak)to raise a fatal exception. If it can find an appropriate package namefor a class method lookup, it will include the results from aFETCH_type_ATTRIBUTES call in its return list, as described inPackage-specific Attribute Handling below.Otherwise, only built-in attributes will be returned.

  • reftype

    This routine expects a single parameter--a reference to a subroutine orvariable. It returns the built-in type of the referenced variable,ignoring any package into which it might have been blessed.This can be useful for determining the type value which forms part ofthe method names described in Package-specific Attribute Handling below.

Note that these routines are not exported by default.

Package-specific Attribute Handling

WARNING: the mechanisms described here are still experimental. Do notrely on the current implementation. In particular, there is no provisionfor applying package attributes to 'cloned' copies of subroutines used asclosures. (See Making References in perlref for information on closures.)Package-specific attribute handling may change incompatibly in a futurerelease.

When an attribute list is present in a declaration, a check is made to seewhether an attribute 'modify' handler is present in the appropriate package(or its @ISA inheritance tree). Similarly, when attributes::get iscalled on a valid reference, a check is made for an appropriate attribute'fetch' handler. See EXAMPLES to see how the "appropriate package"determination works.

The handler names are based on the underlying type of the variable beingdeclared or of the reference passed. Because these attributes areassociated with subroutine or variable declarations, this deliberatelyignores any possibility of being blessed into some package. Thus, asubroutine declaration uses "CODE" as its type, and even a blessedhash reference uses "HASH" as its type.

The class methods invoked for modifying and fetching are these:

  • FETCH_type_ATTRIBUTES

    This method is called with two arguments: the relevant package name,and a reference to a variable or subroutine for which package-definedattributes are desired. The expected return value is a list ofassociated attributes. This list may be empty.

  • MODIFY_type_ATTRIBUTES

    This method is called with two fixed arguments, followed by the list ofattributes from the relevant declaration. The two fixed arguments arethe relevant package name and a reference to the declared subroutine orvariable. The expected return value is a list of attributes which werenot recognized by this handler. Note that this allows for a derived classto delegate a call to its base class, and then only examine the attributeswhich the base class didn't already handle for it.

    The call to this method is currently made during the processing of thedeclaration. In particular, this means that a subroutine reference willprobably be for an undefined subroutine, even if this declaration isactually part of the definition.

Calling attributes::get() from within the scope of a null packagedeclaration package ; for an unblessed variable reference willnot provide any starting package name for the 'fetch' method lookup.Thus, this circumstance will not result in a method call for package-definedattributes. A named subroutine knows to which symbol table entry it belongs(or originally belonged), and it will use the corresponding package.An anonymous subroutine knows the package name into which it was compiled(unless it was also compiled with a null package declaration), and so itwill use that package name.

Syntax of Attribute Lists

An attribute list is a sequence of attribute specifications, separated bywhitespace or a colon (with optional whitespace).Each attribute specification is a simplename, optionally followed by a parenthesised parameter list.If such a parameter list is present, it is scanned past as for the rulesfor the q() operator. (See Quote and Quote-like Operators in perlop.)The parameter list is passed as it was found, however, and not as per q().

Some examples of syntactically valid attribute lists:

  1. switch(10,foo(7,3)) : expensive
  2. Ugly('\(") :Bad
  3. _5x5
  4. lvalue method

Some examples of syntactically invalid attribute lists (with annotation):

  1. switch(10,foo()# ()-string not balanced
  2. Ugly('(')# ()-string not balanced
  3. 5x5# "5x5" not a valid identifier
  4. Y2::north# "Y2::north" not a simple identifier
  5. foo + bar# "+" neither a colon nor whitespace

EXPORTS

Default exports

None.

Available exports

The routines get and reftype are exportable.

Export tags defined

The :ALL tag will get all of the above exports.

EXAMPLES

Here are some samples of syntactically valid declarations, with annotationas to how they resolve internally into use attributes invocations byperl. These examples are primarily useful to see how the "appropriatepackage" is found for the possible method lookups for package-definedattributes.

1.

Code:

  1. package Canine;
  2. package Dog;
  3. my Canine $spot : Watchful ;

Effect:

  1. use attributes ();
  2. attributes::->import(Canine => \$spot, "Watchful");
2.

Code:

  1. package Felis;
  2. my $cat : Nervous;

Effect:

  1. use attributes ();
  2. attributes::->import(Felis => \$cat, "Nervous");
3.

Code:

  1. package X;
  2. sub foo : lvalue ;

Effect:

  1. use attributes X => \&foo, "lvalue";
4.

Code:

  1. package X;
  2. sub Y::x : lvalue { 1 }

Effect:

  1. use attributes Y => \&Y::x, "lvalue";
5.

Code:

  1. package X;
  2. sub foo { 1 }
  3. package Y;
  4. BEGIN { *bar = \&X::foo; }
  5. package Z;
  6. sub Y::bar : lvalue ;

Effect:

  1. use attributes X => \&X::foo, "lvalue";

This last example is purely for purposes of completeness. You should notbe trying to mess with the attributes of something in a package that'snot your own.

MORE EXAMPLES

1.
  1. sub MODIFY_CODE_ATTRIBUTES {
  2. my ($class,$code,@attrs) = @_;
  3. my $allowed = 'MyAttribute';
  4. my @bad = grep { $_ ne $allowed } @attrs;
  5. return @bad;
  6. }
  7. sub foo : MyAttribute {
  8. print "foo\n";
  9. }

This example runs. At compile timeMODIFY_CODE_ATTRIBUTES is called. In thatsubroutine, we check if any attribute is disallowed and we return a list ofthese "bad attributes".

As we return an empty list, everything is fine.

2.
  1. sub MODIFY_CODE_ATTRIBUTES {
  2. my ($class,$code,@attrs) = @_;
  3. my $allowed = 'MyAttribute';
  4. my @bad = grep{ $_ ne $allowed }@attrs;
  5. return @bad;
  6. }
  7. sub foo : MyAttribute Test {
  8. print "foo\n";
  9. }

This example is aborted at compile time as we use the attribute "Test" whichisn't allowed. MODIFY_CODE_ATTRIBUTESreturns a list that contains a singleelement ('Test').

SEE ALSO

Private Variables via my() in perlsub andSubroutine Attributes in perlsub for details on the basic declarations;use for details on the normal invocation mechanism.

 
Source : perldoc.perl.org - Official documentation for the Perl programming language
Site maintained by Jon Allen (JJ)     See the project page for more details
Documentation maintained by the Perl 5 Porters
(Sebelumnya) Return elapsed time for self a ...Replace functions with ones th ... (Berikutnya)