使用Perl访问数组元素的变量

时间:2019-02-05 20:09:17

标签: arrays perl multidimensional-array

我试图在perl中访问数组中的特定变量成员。

my $array = [];
@{$array} = (
             { 'family'  => "abc", 
               'roles'   => {},
             },
             { 'family'  => "def", 
               'roles'   => {
                              'member'=>["1234"],
                            },
             },
            );

我尝试使用

访问值
foreach (@{$array}){
   print " $_->{'family'} \n"; 
   #This is printing the family value 
}

有人可以向我解释如何访问成员字段。我尝试使用$ _-> roles-> {'member'},但这似乎不起作用。这里的任何输入都会有很大的帮助。

我得到以下输出。.我没有任何错误。

哈希(0x268d35)->角色-> {'memeber'}

1 个答案:

答案 0 :(得分:2)

尝试

# hash ref, key 'family' pointing to scalar
print $_->{family}, "\n";
# hash ref, key 'roles' pointing to hash ref,
#    key 'members' pointing to array ref 
print @{ $_->{roles}->{member} }, "\n";

您的哈希引用被插入到一个字符串中,因此被插入HASH(...)

根据您的代码完成代码示例:

#!/usr/bin/perl
use strict;
use warnings;

my $array = [
    {
        family => "abc",
        roles  => {},
    },
    {
        family => "def",
        roles  => {
            member => ["1234"],
        },
    },
];

for my $hash_ref (@{ $array }) {
    print "family ", $hash_ref->{family}, "\n";
    while (my($key, $value) = each %{ $hash_ref->{roles} }) {
        print "role '${key}' @{ $value }\n";
    }
}

exit 0;

试运行

$ perl dummy.pl
family abc
family def
role 'member' 1234