2011-10-25 37 views
0

我有兩個散列,文件夾名作爲鍵和其各自的文件作爲數組。但是我無法訪問getMissingFiles子文件中傳遞的散列的數組元素(請參閱錯誤消息的註釋)。訪問傳遞散列的數組元素

哈希表進行比較:

# contains all files 
%folderWithFiles1 = 
(
    foldername1 => [ qw(a b c d e f g h i j k l m n o p) ], 
    foldername2 => [ qw(a b c d e f g h i j k l m n) ], 
) 

%folderWithFiles2 = 
(
    foldername1 => [ qw(a b d e h i l m n p) ], 
    foldername2 => [ qw(a d f g h j m) ], 
) 

比較子程序(獲得失蹤HASH2不在HASH1文件):

sub getMissingFiles() 
{ 
    my ($hash1, $hash2) = shift; # is it working? 
    #my $hash1 = shift; # or do you have to do it separately? 
    #my $hash2 = shift; 
    my $flag = 0; 
    my @missingFiles; 

    foreach my $folder (sort(keys %{$hash1}))# (sort(keys %hash1)) not possible? 
    { 
     for (my $i = 0; $i < @$hash1{$folder}; $i++) 
     { 
      foreach my $folder2 (sort(keys %{$hash2})) 
      { 
       foreach my $file2 (@$hash2{$folder2}) 
       { 
        if ($hash1{$folder}[$i] == $file2) # Error: Global symbol "%hash1" requires explicit package name 
        { 
         $flag = 1; 
         last; 
        } 
       } 
       if (0 == $flag) 
       { 
        push(@missingFiles, $hash1{$folder}[$i]); # Error: Global symbol "%hash1" requires explicit package name 
       } 
       else 
       { 
        $flag = 0; 
       } 
      } 
     } 
    } 
    return @missingFiles; 
} 

調用函數:

@missingFiles = &getMissingFiles(\%hash1, \%hash2); 
  • 是:「my($ hash1,$ hash2)= shift;」正確還是你必須單獨做?
  • 爲什麼「foreach my $ folder(sort(keys%hash1))」不可能?
  • 有比使用4循環更有效的方法嗎?

回答

1

在getMissingFiles(),就像你解引用$hash1$hash2拿到鑰匙,還需要提領他們得到的值:

@folder_files = @{ $hash1->{$folder1} }; 

或替代,

@folder_files = @{ $$hash1{$folder} }; 

你可以這樣做來獲取單個文件:

$file = $hash1->{$folder}[$i]; 
1

調用語法是不完全正確 - 你想

my ($hash1, $hash2) = @_; 

或許

my $hash1 = shift; 
my $hash2 = shift; 

移位功能只會給你的第一個值,所以你需要你的建議調用兩次,或者如果您想一次性採集更多值,請訪問參數列表@_