从模块导入数据
Import Data from Module
我给了一个文件 testconf.pm ,里面除了
什么都没有
my $item = {
'default' => {
'General' => { 'item1' => 'config1',
'item2' => 'config2'
}
}
};
在第二个文件 main.pl 中,我想为接下来的处理步骤加载哈希,
我尝试了一些东西,比如
use testconfig;
use Data::Dumper;
my $config;
$config = testconfig::item;
print Dumper $config;
但是我无法使用 testconf 中的数据。不幸的是,我无法使用我们的 instea of my 等使用导出器或 packagedeclaration 扩展 testconf.pm,因为这个文件必须保持这样。我怎样才能从 main.pl 中的项目中获取值(顺便说一句。我需要访问数据,而不仅仅是转储数据)
如果文件的结构不允许 do
工作,您可以阅读该文件,进行任何必要的更改,然后 eval
:
open my $fh, '<', 'testconfig.pm';
$/ = undef;
my $testconfig = <$fh>;
# changes to the $testconfig source go here
my $config = eval $testconfig;
你特别告诉 Perl 将变量的范围(它出现的地方)限制在文件中,所以你不能。
如果那是整个文件,您可以相信对 $item
的赋值是文件的最后一条语句,方法是更改
do("testconf.pm")
or die($@ || $!);
至
my $item = do("testconf.pm")
or die($@ || $!);
我给了一个文件 testconf.pm ,里面除了
什么都没有my $item = {
'default' => {
'General' => { 'item1' => 'config1',
'item2' => 'config2'
}
}
};
在第二个文件 main.pl 中,我想为接下来的处理步骤加载哈希, 我尝试了一些东西,比如
use testconfig;
use Data::Dumper;
my $config;
$config = testconfig::item;
print Dumper $config;
但是我无法使用 testconf 中的数据。不幸的是,我无法使用我们的 instea of my 等使用导出器或 packagedeclaration 扩展 testconf.pm,因为这个文件必须保持这样。我怎样才能从 main.pl 中的项目中获取值(顺便说一句。我需要访问数据,而不仅仅是转储数据)
如果文件的结构不允许 do
工作,您可以阅读该文件,进行任何必要的更改,然后 eval
:
open my $fh, '<', 'testconfig.pm';
$/ = undef;
my $testconfig = <$fh>;
# changes to the $testconfig source go here
my $config = eval $testconfig;
你特别告诉 Perl 将变量的范围(它出现的地方)限制在文件中,所以你不能。
如果那是整个文件,您可以相信对 $item
的赋值是文件的最后一条语句,方法是更改
do("testconf.pm")
or die($@ || $!);
至
my $item = do("testconf.pm")
or die($@ || $!);