【问题标题】:Access array elements of passed hash访问传递的哈希的数组元素
【发布时间】: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


    【解决方案1】:

    在 getMissingFiles() 中,就像您取消引用 $hash1$hash2 以获取密钥一样,您还需要取消引用它们以获取值:

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

    或者,

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

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

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

    【讨论】:

      【解决方案2】:

      那个调用语法不太正确——你想要

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

      或许

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

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

      【讨论】:

        猜你喜欢
        • 2013-11-01
        • 2021-08-01
        • 1970-01-01
        • 1970-01-01
        • 2013-08-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-03-22
        相关资源
        最近更新 更多