我有两个哈希,其中foldername作为键,其各自的文件作为数组。但我无法访问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 ) ],
)
比较子程序(从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);
答案 0 :(得分:1)
在getMissingFiles()中,就像您取消引用$hash1
和$hash2
来获取密钥一样,您还需要取消引用它们以获取值:
@folder_files = @{ $hash1->{$folder1} };
或者,
@folder_files = @{ $$hash1{$folder} };
您可以这样做以获取单个文件:
$file = $hash1->{$folder}[$i];
答案 1 :(得分:1)
调用语法不太正确 - 你想要
my ($hash1, $hash2) = @_;
或者
my $hash1 = shift;
my $hash2 = shift;
shift函数只会给你第一个值,所以你需要按照你的建议调用两次,或者如果你想一次性获取超过值的话,可以访问参数列表@_
。