【发布时间】:2011-12-14 18:02:52
【问题描述】:
我有两个散列,其中一个文件夹名称作为键,其各自的文件作为一个数组。但我无法访问 getMissingFiles 子中传递的哈希的数组元素(有关错误消息,请参阅 cmets)。
要比较的哈希:
# 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);
- 是:“我的 ($hash1, $hash2) = shift;”正确还是必须分开做?
- 为什么“foreach my $folder (sort(keys %hash1))”不可能?
- 有没有比使用 4 个循环更有效的方法?
【问题讨论】:
标签: arrays perl hash reference