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

Vin*_*R M 0 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'
                   }
);
Run Code Online (Sandbox Code Playgroud)

而我的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";
   }
}
Run Code Online (Sandbox Code Playgroud)

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

"在file2.pl的hash元素中使用未初始化的值"

当我尝试访问这样的哈希:

for $key1 (keys %{$file1::hash{$key1}})
Run Code Online (Sandbox Code Playgroud)

请帮助.

Zai*_*aid 6

这是因为$key1没有定义.

你打算用%{ $file1::hash{$key} }.


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

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

   print "$key\n";

   for my $key1 (keys %{$file1::hash{$key1}}){
       print "$key1\n";
   }
}
Run Code Online (Sandbox Code Playgroud)

信息

Global symbol "$key1" requires explicit package name
Run Code Online (Sandbox Code Playgroud)

  • @VinodRM:`我的$ key1`是*声明*,而不是*定义*.Zaid的意思是你试图在它有一个值之前使用`$ key1`作为哈希键.$ for key1(key%{$ file1 :: hash {$ key1}})`的行应该是`for $ key1(keys%{$ file1 :: hash {$ key}})` (2认同)