不同类型值的 Perl Hash

Perl Hash of different types of value

我有一个散列。我需要访问 Key1 值中的数组。它实际上是一个进一步哈希的数组。

$VAR1 = {
          'student_name' => 'abc',
          'gender'       => 'male',
          'parent_name'  => {
                              'mothe'  => 'jane',
                              'father' => 'victor'
                            },
          'contact'      => [
                              {
                                'phone'   => '12345',
                                'address' => 'home ref'
                              },
                            ]
};

我尝试提取 $contact 数据,如下所示:

my $contact = $hash_name->{"contact"}

以下是我收到的错误:

Not a hash reference;

问题是散列和散列引用之间的区别。

哈希是这样初始化和访问的:

my %hash = ( foo => 123 );
print $hash{'foo'}, "\n";

Hashref 是这样的;您使用 -> 运算符访问值:

my $href = { foo => 123 };
print $href->{'foo'}, "\n";

在嵌套数据结构中,嵌套项只能是标量,不能是散列或数组。 Hashrefs 和 arrayrefs 是标量的类型。

嵌套结构的“最外层”级别仍然可以是散列或数组,这就是您所处的情况。

my $contact             = $hash_name{'contact'};
my $first_contact       = $hash_name{'contact'}->[0];
my $first_contact_phone = $hash_name{'contact'}->[0]->{'phone'};

Perl 在深入嵌套数据结构时允许 shorthand。第一关后,->可以省略

my $contact             = $hash_name{'contact'};
my $first_contact       = $hash_name{'contact'}[0];
my $first_contact_phone = $hash_name{'contact'}[0]{'phone'};