繁体   English   中英

访问传递哈希的数组元素

[英]Access array elements of passed hash

我有两个哈希,其中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中获取缺少的文件,不在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个循环更有效的方法?

在getMissingFiles()中,就像你取消引用$hash1$hash2来获取键一样,你还需要取消引用它们来获取值:

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

或者,

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

你可以这样做来获取单个文件:

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

那个调用语法不太对 - 你想要的

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

也许

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

shift函数只会给你第一个值,所以你需要按照你的建议调用两次,或者如果你想一次性获取超过值的值,则访问参数列表@_

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM