我有一个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
}
}
有人可以告诉我这里出了什么问题吗?另外,如果我有多键哈希,在这种情况下哈希被'number'和'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";
}
谢谢, 新手
答案 0 :(得分:6)
my %hash;
$hash{'number'}{'even'} = [24, 44, 38, 36];
$hash{'number'}{'odd'} = [23, 43, 37, 35];
%hash
是一个哈希,其键是字符串('number'
),其值是哈希引用。
foreach my $key (keys %hash{'number'})
{
print "Key: $key\n";
}
要引用属于%hash
的值,您要撰写$hash{'number'}
,而不是%hash{'number'}
。
但是$hash{'number'}
是哈希引用,而不是哈希。要引用它引用的哈希,可以这样写:
%{$hash{'number'}}
把这一切放在一起:
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";
}
将产生此输出:
Key: even
Key: odd
(可能不是那个顺序)。
答案 1 :(得分:0)
您可以这样做:
#!/usr/bin/perl -w
use strict;
use warnings;
my %hash;
$hash{'number'}{'even'} = [24, 44, 38, 36];
$hash{'number'}{'odd'} = [23, 43, 37, 35];
foreach my $i(keys %hash){
print $i;
foreach my $j(keys %{$hash{$i}}){
print "\t".$j."\t";
print join(" ",@{$hash{'number'}{$j}})."\n";
}
}