如何从 Moose 包中导出子例程?
如何从 Moose 包中导出正常的非 OO 子例程?在常规包中,我会使用 Exporter
、@ISA
和 @EXPORT
来完成此操作。
How can I export a normal, non-OO subroutine from a Moose package? In a regular package, I'd do it with Exporter
, @ISA
and @EXPORT
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
Moose 用于构建类和角色。虽然从技术上讲您也可以导出函数,但这不一定是最好的主意。
下面是一个示例 Moose 类,它还导出一个函数。
MyApp/Widget.pm
以下是您可以如何使用它:
请注意,尽管
is_widget
是一个可导出函数,但它也可以作为方法来调用!在这种情况下,这是一个功能而不是一个错误,但通常这会带来不便。更好的想法可能是创建两个单独的包:一个用于您的类,另一个用于您的可导出函数。
MyApp/Widget.pm
MyApp/Util.pm
您可以像这样调用您的包:
因为 Moose 类和 Exporter 现在完全分离,所以您不能不再调用
$w->is_widget
— 它完全是一个函数,不再是一个方法。Moose is for building classes and roles. While you technically can also export functions, it's not necessarily the best idea.
Here's an example Moose class which also exports a function.
MyApp/Widget.pm
Here's how you might use it:
Note that even though
is_widget
was intended an exportable function, it can also be called as a method! In this case, that's a feature rather than a bug, but often that will be an inconvenience.A better idea might be to create two separate packages: one for your class and one for your exportable functions.
MyApp/Widget.pm
MyApp/Util.pm
And you'd call use your packages like this:
Because the Moose class and the Exporter are now cleanly separated, you can no longer call
$w->is_widget
— it's entirely a function and no longer a method.