从模块导入数据

时间:2015-01-23 15:08:32

标签: perl perl-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等扩展testconf.pm与导出器或packagedeclaration,因为这个文件必须保持这样。我如何从main.pl中的项目中获取值(顺便说一句。我需要访问数据,而不仅仅是转储数据)

2 个答案:

答案 0 :(得分:7)

你特意告诉Perl将变量的范围(它看到的地方)限制在文件中,所以你不能。

如果这是整个文件,您可以依赖于$item的赋值是通过更改

的文件的最后一个语句的事实
do("testconf.pm")
   or die($@ || $!);

my $item = do("testconf.pm")
   or die($@ || $!);

答案 1 :(得分:2)

如果文件的结构不允许do工作,您可以阅读该文件,进行必要的更改并eval

open my $fh, '<', 'testconfig.pm';
$/ = undef;
my $testconfig = <$fh>;
# changes to the $testconfig source go here
my $config = eval $testconfig;