如何访问具有哈希引用和数组引用的哈希元素

时间:2014-06-06 15:35:50

标签: arrays perl hash

我有一个散列,其中包含几个级别的散列,其中包含数组和散列引用。 所以我编写了一个类似下面的代码来使用ref($var)的输出来访问它们。 %c是我的哈希值。在for循环的第3级之后,我得到哈希引用和数组引用,所以我想访问数组元素。 我在我的else循环中使用my $array_ref = [%$new_values];来访问数组元素。 但我收到了以下错误:

Type of arg 1 to keys must be hash (not array dereference)

我的代码:

foreach my $item ( keys %c ) {
    print "$item: \n";    # print keys
    my $hash = $c{$item};

    foreach my $key2 ( keys %$hash ) {
        print "\t", $key2, "\n\t";    # print keys
        my $hashref = $hash->{$key2};
        my $myref = ref($hashref);
        #print("ref type is $myref\n");

        foreach my $key3 (keys %{$hashref}) {
            my $values = $hashref->{$key3};
            my $myref1 = ref($values);
            # print("ref type is $myref1\n");

            foreach my $key4 (keys %{$values}) {
                my $new_values = $values->{$key4};
                my $myref2 = ref($new_values);
                if ($myref2 eq HASH) {
                     #print("ref type is $myref2\n");
                     print "\t", join "\t", map { %$_ } %$new_values;    
                     print "\n";
                }
                elsif ($myref2 eq ARRAY) {
                    print "\t", join "\t", map { @$_ } @$new_values; 
                    print "\n";
                    my $array_ref = [%$new_values];
                    my $new_type = ref($array_ref);
                    print "$new_type\n";
                    foreach my $key_array ( keys @$array_ref) {
                        print "$key_array\n";
                    }
                    print "\t", $key_array, "\n\t";     
                }
            }
        }
    }
} 

1 个答案:

答案 0 :(得分:1)

print "\t", join "\t", map { %$_ } %$new_values;

print "\t", join "\t", map { @$_ } @$new_values; 

包含两个解除引用而不是一个,map {...}, %hash会将所有键和值传递给块,因此尝试取消引用块内的键将始终失败,因为它不能作为参考。

目前尚不清楚这些应该是什么。大概你只想要$new_values是数组引用的情况下的值列表,所以你想要

print "\t", join "\t", @$new_values;

或只是

print "\t$_" for @$new_values; 

但是在哈希的情况下,你想看到键还是只看到值?如果是后者那么你应该写

print "\t", join "\t", values %$new_values;

但是有很多方法可以转储每个哈希元素的键和值。这是一个建议

print "\t", join ', ', map "$_ => '$new_values->{$_}'", keys %$new_values;

我无法理解你在上一节中的意图

my $array_ref = [%$new_values];
my $new_type = ref($array_ref);
print "$new_type\n";
foreach my $key_array ( keys @$array_ref) {
   print "$key_array\n";
}
print "\t", $key_array, "\n\t";

但很明显,您尝试将$new_values取消引用为my $array_ref = [%$new_values]中的哈希值会失败,因为这是在您确认$new_values的块内数组参考。

此外,行my $new_type = ref($array_ref)似乎是多余的,因为您刚刚创建了$array_ref作为数组引用,因此$new_type 总是ARRAY

最后,您for循环keys @$array_ref可能不会按照您的想法执行操作。在Perl 5的第12版之前,这是一个语法错误,但从那时起它将返回数组索引列表,因此它与0 .. $#$array_ref相同。

如果你更好地解释这一部分,那么我很乐意帮助你让它发挥作用。