2011-10-25 36 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; 

移位功能只会给你的第一个值,所以你需要你的建议调用两次,或者如果您想一次性采集更多值,请访问参数列表@_