在我的一个主要(或主要)例程中,我有两个或更多个哈希值。我希望子程序foo()接收这些可能的多个哈希值作为不同的哈希值。现在我没有偏好,如果他们按价值或作为参考。我在最近几个小时内一直在努力,并且会感谢帮助,所以我不必为PHP留下perl! (我正在使用mod_perl,或将是)
现在我已经得到了一些答案,如图所示
来自http://forums.gentoo.org/viewtopic-t-803720-start-0.html
# sub: dump the hash values with the keys '1' and '3'
sub dumpvals
{
foreach $h (@_)
{
print "1: $h->{1} 3: $h->{3}\n";
}
}
# initialize an array of anonymous hash references
@arr = ({1,2,3,4}, {1,7,3,8});
# create a new hash and add the reference to the array
$t{1} = 5;
$t{3} = 6;
push @arr, \%t;
# call the sub
dumpvals(@arr);
我只想扩展它,以便在转储中我可以做这样的事情:
foreach my %k ( keys @_[0]) {
# use $k and @_[0], and others
}
语法错误,但我想你可以告诉我我正在尝试获取第一个哈希(hash1或h1)的密钥,并迭代它们。
如何在上面的代码片段中执行此操作?
答案 0 :(得分:4)
我相信这就是你要找的东西:
sub dumpvals {
foreach my $key (keys %{$_[0]}) {
print "$key: $_[0]{$key}\n";
}
}
参数数组的元素是标量,因此您可以$_[0]
而不是@_[0]
访问它。
键对哈希值进行操作,而非散列引用,因此您需要使用%
当然,密钥是标量,而不是哈希值,因此您使用的是my $key
,而不是my %key
。
答案 1 :(得分:3)
要让dumpvals
转储传递给它的所有哈希的内容,请使用
sub dumpvals {
foreach my $h (@_) {
foreach my $k (keys %$h) {
print "$k: $h->{$k}\n";
}
}
}
在你的问题中调用它的输出是
1: 2 3: 4 1: 7 3: 8 1: 5 3: 6