为什么其他包不调用 Perl 属性处理程序?
我在 Attribute::Handlers 上遇到了一个奇怪的问题,看起来像是某种错误:
package MyPackage;
use Attribute::Handlers;
sub UNIVERSAL::foo :ATTR(CODE) {
...
}
当在 MyPackage 中使用时,或者从使用 MyPackage 的脚本的主包中使用时,只要编译器遇到 foo 的函数,就会调用 foo 处理程序然而
sub bar:foo {
...
}
,我有另一个包,在一个单独的 .pm 文件中,它使用 MyPackage。编译器接受“:foo”属性,但处理程序不被调用。
我尝试在 MyPackage 中编写一个导入函数,将 foo 处理程序导出到调用者的命名空间,但这似乎没有帮助。
有人能理解这一点吗?这几天我一直在绞尽脑汁思考如何解决这个问题。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
默认情况下,属性处理程序在编译阶段后在 CHECK 块中调用。
如果“using”包使用
eval "use packagename";
,那么只会执行BEGIN 块。 CHECK 块不会被执行,属性处理程序也不会被调用。尝试使用 ATTR(CODE,BEGIN) 来执行 BEGIN 块中的处理程序。
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.我不知何故完全错过了你昨天帖子中的 Attribute::Handlers - 正如我对此答案的旧版本的评论中提到的,也许将
use MyPackage
包装在BEGIN
块中将使事情得到妥善解决。我不确定您为什么选择将
foo()
属性处理程序放入UNIVERSAL
中 - 这是尝试使其正常工作的一步吗?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 aBEGIN
block will cause things to be resolved properly.I'm unsure as to why you chose to put the
foo()
attribute handler inUNIVERSAL
- was that a step toward trying to get it to work?