访问perl中另一个文件中定义的哈希哈希并打印它

时间:2013-03-28 09:35:22

标签: perl hash-of-hashes

现在我的file1包含哈希哈希,如下所示:

package file1;

our %hash = (
    'articles' =>  {
                       'vim' => '20 awesome articles posted',
                       'awk' => '9 awesome articles posted',
                       'sed' => '10 awesome articles posted'
                   },
    'ebooks'   =>  {
                       'linux 101'    => 'Practical Examples to Build a Strong Foundation in Linux',
                       'nagios core'  => 'Monitor Everything, Be Proactive, and Sleep Well'
                   }
);

我的file2.pl包含

#!/usr/bin/perl
use strict;
use warnings;

require 'file1';

my $key;
my $key1;

for $key (keys %file1::hash){
   print "$key\n";

   for $key1 (keys %{$file1::hash{$key1}}){
   print "$key1\n";
   }
}

现在我的问题是,我收到错误

“在file2.pl的哈希元素中使用未初始化的值”

当我尝试像这样访问哈希时:

for $key1 (keys %{$file1::hash{$key1}})

请帮助。

1 个答案:

答案 0 :(得分:6)

这是因为$key1未定义。

您打算改用%{ $file1::hash{$key} }


请注意,如果您避免预先声明$key1strict pragma可以在编译时捕获它:

for my $key (keys %file1::hash){

   print "$key\n";

   for my $key1 (keys %{$file1::hash{$key1}}){
       print "$key1\n";
   }
}

<强>消息

Global symbol "$key1" requires explicit package name