Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why don't Perl attribute handlers get called from other packages?

I am having a strange problem with Attribute::Handlers that looks like some kind of bug:

package MyPackage;

use Attribute::Handlers;

sub UNIVERSAL::foo :ATTR(CODE) {
  ...
}

When used in MyPackage, or from the main package of a script that uses MyPackage, the foo handler is called whenever the compiler comes across a function of the form

sub bar:foo {
 ...
}

However, I have another package, in a separate .pm file, that uses MyPackage. The compiler accepts the ":foo" attribute, but the handler is not called.

I tried writing an import function in MyPackage that exports the foo handler to the caller's namespace, but that doesn't seem to help.

Can anyone make sense of this? I've been racking my brain for the past few days over how to fix this.

like image 565
Rob Avatar asked Oct 25 '22 08:10

Rob


1 Answers

By default, attribute handlers are called in the CHECK block after the compilation phase.

If the "using" package uses eval "use packagename"; then only BEGIN blocks will be executed. CHECK blocks won't be executed, and the attribute handlers won't be called.

Try using ATTR(CODE,BEGIN) to execute the handler in the BEGIN block.

like image 82
salty-horse Avatar answered Nov 10 '22 18:11

salty-horse