访问哈希数组中的类型数组的哈希成员 [英] access hash member of type array within array of hashes
问题描述
我有一个这样的匿名散列数组:
my @ arrayOfHashes =(
{
name =>'foo',
value => ['one','two']
},
{
name =>'bar',
值=> ['two','three']
}
);
我想遍历数组并访问每个哈希中的数组:
foreach(@arrayOfHashes){
print $ _-> {'value'}#ARRAY(0x88489f4)
}
上面打印的值不是我想要的值...我想使用该数组所以它的工作原理是这样的:
print qw(one two)#onetwo
但是,当我像这样使用 qw 时:
my @ arrayOfHashes =(
{
name =>'foo',
qw(one two)
},
{
name =>'bar',
qw(three four)
}
);
运行时出现此错误消息(我使用的是严格模式):
匿名散列元素的奇数个元素位于...
如何引用 foreach 块中的value数组?
所以你有一个你想解引用的数组的引用。当你有一个引用时,相当于 @array
是 @ {$ ref}
,所以
print(@ array \ n);
print(join(',',@array),\\\
);
会是
print(@ {$ _-> {value}} \\\
);
print(join(',',@ {$ _-> {value}}),\\\
);
参考文献:
I have an array of anonymous hashes like this:
my @arrayOfHashes=(
{
name => 'foo',
value => ['one', 'two']
},
{
name => 'bar',
value => ['two', 'three']
}
);
I'm trying to iterate over the array and access the array within each hash:
foreach (@arrayOfHashes) {
print $_->{'value'} # ARRAY(0x88489f4)
}
The value that is printed above is not what I want... I want to use that array so it works like this:
print qw(one two) # onetwo
But, when I use qw like this:
my @arrayOfHashes=(
{
name => 'foo',
qw(one two)
},
{
name => 'bar',
qw(three four)
}
);
I get this error message at runtime (I am using strict mode):
Odd number of elements in anonymous hash at ...
How do I reference the "value" array within the foreach block?
So you have a reference to an array you want to dereference. The equivalent of @array
for when you have a reference is @{ $ref }
, so
print("@array\n");
print(join(', ', @array), "\n");
would be
print("@{ $_->{value} }\n");
print(join(', ', @{ $_->{value} }), "\n");
References:
这篇关于访问哈希数组中的类型数组的哈希成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!