我的结构如下:
$var1=[{a=>B,c=>D},{E=>F,G=>H}];
现在我想遍历第一个哈希及其中的元素。我该怎么做?
当我执行$var1
的转储程序时,它会向我Array
提供@var1
时,它会显示哈希值。
答案 0 :(得分:2)
您可以像对待任何其他数组一样遍历数组,并且您将获得哈希引用。然后像使用普通哈希引用一样迭代每个哈希的键。
类似的东西:
foreach my $hash (@{$var1}) {
foreach my $key (keys %{$hash}) {
print $key, " -> ", $hash->{$key}, "\n";
}
}
答案 1 :(得分:2)
首先,你将使用包含裸字的变量声明来运行Perl的严格模式。
考虑到这一点,请填写下面给出的注释示例。
use strict;
my $test = [{'a'=>'B','c'=>'D'},{'E'=>'F','G'=>'H'}];
# Note the @{ $test }
# This says "treat this scalar reference as a list".
foreach my $elem ( @{ $test } ){
# At this point $elem is a scalar reference to one of the anonymous
# hashes
#
# Same trick, except this time, we're asking Perl
# to treat the $elem reference as a reference to hash
#
# Hence, we can just call keys on it and iterate
foreach my $key ( keys %{ $elem } ){
# Finally, another bit of useful syntax for scalar references
# The "point to" syntax automatically does the %{ } around $elem
print "Key -> $key = Value " . $elem->{$key} . "\n";
}
}
答案 2 :(得分:1)
C:\wamp\bin\perl\bin\PERL_2~1\BASIC_~1\REVISION>type traverse.pl
my $var1=[{a=>"B", c=>"D"},{E=>"F", G=>"H"}];
foreach my $var (@{$var1}) {
foreach my $key (keys(%$var)) {
print $key, "=>", $var->{$key}, "\n";
}
print "\n";
}
C:\wamp\bin\perl\bin\PERL_2~1\BASIC_~1\REVISION>traverse.pl
c=>D
a=>B
G=>H
E=>F
$var1 = []
是对匿名数组的引用
在@
之前使用$var1
sigil,可以访问它所引用的数组。与foreach (@arr) {...}
类似,你会做foreach (@{$var1}) {...}
。
现在,您提供的数组中的元素@{$var1}
也是匿名的(也就是未命名),但它们是匿名哈希,所以就像使用arrayref一样,这里我们{{1}访问%{$hash_reference}
引用的哈希值。在此,$hash_reference
为$hash_reference
。
使用$var
访问哈希后,使用%{$var}
或keys(%$var)
可以轻松访问哈希的密钥。由于返回的结果是一组键,因此我们可以在keys(%{$var})
内使用keys(%{$var})
。
我们使用像foreach (keys(%{$var})) {...}
之类的密钥在匿名哈希中访问标量值,这就是所有代码所做的。
如果您的数组包含匿名的数组哈希,例如:
$hash_reference->{$keyname}
那么,这就是你访问数组值的方式:
$var1=[ { akey=>["b", "c"], mkey=>["n", "o"]} ];
更多,更经常地练习它很快就会很容易将复杂的结构分解成这样的组合。这就是我创建large parser for another software的方式,它充满了你的问题的答案:)
答案 3 :(得分:0)
一眼看到amon上面评论的评论(谢谢,amon!)我能够写下这个小曲子:
#!/usr/bin/perl
# Given an array of hashes, print out the keys and values of each hash.
use strict; use warnings;
use Data::Dump qw(dump);
my $var1=[{A=>"B",C=>"D"},{E=>"F",G=>"H"}];
my $count = 0;
# @{$var1} is the array of hash references pointed to by $var1
foreach my $href (@{$var1})
{
print "\nArray index ", $count++, "\n";
print "=============\n";
# %{$href} is the hash pointed to by $href
foreach my $key (keys %{$href})
{
# $href->{$key} ( ALT: $$href{$key} ) is the value
# corresponding to $key in the hash pointed to by
# $href
# print $key, " => ", $href->{$key}, "\n";
print $key, " => ", $$href{$key}, "\n";
}
print "\nCompare with dump():\n";
dump ($var1);
print "\nJust the first hash (index 0):\n";
# $var1->[0] ( ALT: $$var1[0] ) is the first hash reference (index 0)
# in @{$var1}
# dump ($var1->[0]);
dump ($$var1[0]);
#print "\nJust the value of key A: \"", $var1->[0]->{A}, "\"\n";
#print "\nJust the value of key A: \"", $var1->[0]{A}, "\"\n";
print "\nJust the value of key A: \"", $$var1[0]{A}, "\"\n"