Why don't Perl attribute handlers get called from other packages?
I am having a strange problem with Attribute::Handlers that looks开发者_StackOverflow中文版 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.
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.
I somehow totally missed the Attribute::Handlers in your post yesterday - as mentioned in my comment to the older version of this answer, perhaps wrapping the use MyPackage
in a BEGIN
block will cause things to be resolved properly.
I'm unsure as to why you chose to put the foo()
attribute handler in UNIVERSAL
- was that a step toward trying to get it to work?
精彩评论