Search code examples
perlattributessubroutine

attributes::get() returning empty list?


I've never actually used subroutine attributes in perl before, but it happens that I've found a use for them, so I've been trying to understand how I can use them. In particular, I need to be able to find out, at runtime, what attributes a subroutine has. I've got the following test code, but it outputs only an empty list:

use attributes;

sub MODIFY_CODE_ATTRIBUTES {
    my ($class,$code,@attrs) = @_;

    my $allowed = 'takeshash';
    my @bad = grep { $_ ne $allowed } @attrs;

    return @bad;
}
sub mylog : takeshash {

    my $params = shift;
    my $val = log($params->{'n'}) / log($params->{'base'});

    return $val;
}

use Data::Dumper;
print Dumper [attributes::get(\&mylog)];

Running perl v5.12.4, I get:

$ perl temp.pl
$VAR1 = [];

Solution

  • Looks like your problem is explained by the section on Available Subroutines in the attributes documentation. The explanation for the get subroutine says:

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

    Note the final sentence, where I have added emphasis. Looks like you need to add a FETCH_CODE_ATTRIBUTES subroutine.