【发布时间】:2017-09-29 03:44:56
【问题描述】:
假设我有一个名为Local 的模块,它通过%EXPORT_TAGS 接口导出一个子例程subLocal。
此模块与另一个名为 Remote 的模块密切相关,后者定义了 Local 的用户可能想要导入的子例程。
我有两个要求:
只有当模块
Local的用户正在导入Remote中定义的子例程时,模块Local才应该导入Remote中定义的子例程(通过显式命名导出或使用特定导出标签)
1234563当引用
Local 中定义的子程序时。
我只找到了 req. 2 通过在符号表中添加一个条目,但这种情况总是发生——不管Local 的用户是否真的需要Remote 中的子例程。根据 perldoc,这毫无意义地“污染”了命名空间。
那么在编译或运行时的什么时候我应该尝试从Remote 导入子例程?以及如何以它们出现在本地命名空间中的方式实际导入它们?
这是我目前的方法。模块Local:
package Local;
use strict;
use warnings;
BEGIN
{
require Exporter;
our @ISA = qw| Exporter |;
our @EXPORT_LOCAL = qw| subLocal |;
our @EXPORT_REMOTE = qw| subRemote |;
our @EXPORT_OK = ( @EXPORT_LOCAL, @EXPORT_REMOTE );
our %EXPORT_TAGS =
( all => \@EXPORT_OK, local => \@EXPORT_LOCAL, remote => \@EXPORT_REMOTE );
*subRemote = \&Remote::subRemote; # <-- can I do this conditionally somewhere?
# <-- and is there a better way to put this function in the user's local namespace?
}
use Remote; # <-- can I do this conditionally somewhere?
sub subLocal { return "(local)" }
1;
还有模块Remote:
package Remote;
use strict;
use warnings;
BEGIN
{
require Exporter;
our @ISA = qw| Exporter |;
our @EXPORT_REMOTE = qw| subRemote |;
our @EXPORT_OK = ( @EXPORT_REMOTE );
our %EXPORT_TAGS =
( all => \@EXPORT_OK, remote => \@EXPORT_REMOTE );
}
sub subRemote { return "(remote)" }
1;
【问题讨论】:
-
这对我来说听起来像是一个循环定义。它读起来好像你想1)将
main从Remote导入的标识符导入Local,然后2)导入main由Local从Remote导入的标识符。那是对的吗?如果是这样,那么这听起来像是糟糕的设计,我认为您需要举个例子。 -
你可能想实现你自己的
import。 -
您将无法使用 Exporter。您需要实现自己的
import,或者其他导出管理模块之一可能会有所帮助。 -
@Borodin 不,我只是想实现您的声明 2)。但增加了使该导入有条件的要求
-
说实话,我认为对你来说最好的解决方案就是忘记污染你的命名空间!您不打算拥有数百个子例程吗?
标签: perl perl-module perl-exporter