2013-03-28 40 views
0

現在我的文件1包含哈希散列,如下圖所示:訪問在另一個perl的文件中定義的哈希散列進行打印

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}}) 

請幫助。

回答

6

這是因爲$key1沒有定義。

您打算使用%{ $file1::hash{$key} }代替。


請注意,如果您避免預先聲明$key1,該strict編譯可以在編譯時抓住它:

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 
+0

我已經定義了$ KEY1爲 my $ key1; – 2013-03-28 09:46:55

+2

@VinodRM:'我的$ key1'是*聲明*,而不是*定義*。 Zaid的含義是,你在嘗試使用'$ key1'作爲一個散列鍵,然後它有一個值。對於$ key1(鍵%{$ file1 :: hash {$ key1}})''的行應該是'for $ key1(keys%{$ file1 :: hash {$ key}})' – Borodin 2013-03-28 09:59:39

+0

@Borodin:你的觀點。非常感謝 – 2013-03-28 10:35:58