【发布时间】:2014-07-06 11:17:30
【问题描述】:
我正在重构一些旧的、糟糕的 Perl 代码。在许多地方,存储在外部.pl 文件中的数据如下:
sub data{{ huge => 'datastructure', etc => '...' }};
1;
是这样导入的:
require 'file_with_data.pl';
my $data = data();
我无法更改这些数据的存储方式,但我将所有这些 require 逻辑移动到一个包中,这样任何人都可以访问这些数据。
我的问题是,我必须循序渐进地做到这一点,即在一段时间内,一些模块会使用旧的、丑陋的方式,而另一些模块会使用新的、稍微不那么丑陋的方式。
这是我的新包中的一种方法:
sub load_from_subroutine {
no strict 'refs';
my ($self, $file, $subroutine) = @_;
my $data;
try {
if (exists $INC{$file}) {
die "What should I do now?"; # <-- this is what I want to change
}
else {
untaint $file;
require $file;
if (defined &$subroutine) {
$data = &$subroutine;
}
else {
die "Subroutine $subroutine is not defined";
}
}
}
catch {
croak "Unable to load resource from file $file: $_";
};
return $data;
}
如果exists $INC{$file} 测试为真,我可以使用什么技巧来获得&$subroutine?暗示,在这个命名空间中,defined &$subroutine 是假的。
临时代码
与此同时,这是我正在使用的:
warn "Doing dirty trick in order to be able to load $file!\n";
my $tmp = '/tmp/data' . time . rand(100) . '.pl';
copy $file, $tmp;
require $tmp;
# do the loading stuff as shown...
unlink $tmp;
这真的很糟糕,我渴望更好的解决方案。
【问题讨论】:
标签: perl namespaces include require