【发布时间】:2012-02-18 01:23:35
【问题描述】:
我有一个像这样索引的 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
但是,当我将数组 ref 传递给函数并在那里打印时,它会打印值:
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";
}
谢谢, 新手
【问题讨论】:
标签: perl