多加密哈希我有我索引这样一个Perl哈希:打印在Perl
my %hash;
$hash{'number'}{'even'} = [24, 44, 38, 36];
$hash{'number'}{'odd'} = [23, 43, 37, 35];
当我尝试打印键名这样的:
foreach my $key (keys %hash{'number'})
{
print "Key: $key\n";
}
我得到以下错误:
Type of arg 1 to keys must be hash (not hash slice) at test.pl
然而,当我传递数组引用到一个函数,并打印在那里,它打印的值:
test(\%hash);
sub test
{
my ($hash) = @_;
foreach my $key (keys %{$hash->{'number'}})
{
print "Key: $key\n"; #outputs: even odd
}
}
有人能让我知道这里出了什么问题吗?此外,如果我有我在这个情况下哈希由两个“数字”索引和多加密散列“偶”或“奇”如果我做这样的事情:
foreach my $key (keys %hash)
{
print "First Key: $key\n"; #Outputs number
}
那时,我总是得到'数字'作为输出权,我永远不会得到'偶数','奇数'作为输出,对吗?这仅仅是知道好的编码做法:)
这是全码:
sub test
{
my ($hash) = @_;
foreach my $key (keys %{$hash->{'number'}})
{
print "Key: $key\n";
}
}
my %hash;
$hash{'number'}{'even'} = [24, 44, 38, 36];
$hash{'number'}{'odd'} = [23, 43, 37, 35];
test(\%hash);
foreach my $key (keys %hash)
{
print "First Key: $key\n";
}
foreach my $key (keys %hash{'number'})
{
print "Key: $key\n";
}
感谢, 新手
而且,为了学术上的兴趣,这里有更多关于哈希切片的信息,这是原始代码意外做的事情:http://perldoc.perl.org/perldata.html#Slices – fennec 2012-02-18 01:39:21
OMG ...就是这样!我在想整个名字是一个关键!感谢您的详细解释。它真的帮助:) – Richeek 2012-02-18 01:39:26
如果您使用5.14或更高版本,现在可以在引用上使用键,值,每个按钮,弹出,切片,移位和不移位功能。这意味着'keys%{$ hash {k}}'可以被重写为'keys $ hash {k}'。麾! – kbenson 2012-02-18 02:03:27