在Perl中打印多键哈希

Ric*_*eek 3 perl

我有一个perl哈希,我正在索引这样:

my %hash;
$hash{'number'}{'even'} = [24, 44, 38, 36];
$hash{'number'}{'odd'} = [23, 43, 37, 35];
Run Code Online (Sandbox Code Playgroud)

当我尝试打印这样的关键名称时:

foreach my $key (keys %hash{'number'})
{
   print "Key: $key\n";
}
Run Code Online (Sandbox Code Playgroud)

我收到以下错误:

Type of arg 1 to keys must be hash (not hash slice) at test.pl
Run Code Online (Sandbox Code Playgroud)

但是当我将数组ref传递给函数并在那里打印时,它会打印值:

test(\%hash);

sub test
{
   my ($hash) = @_;
   foreach my $key (keys %{$hash->{'number'}})
   {
       print "Key: $key\n";     #outputs: even odd
   }
}
Run Code Online (Sandbox Code Playgroud)

有人可以告诉我这里出了什么问题吗?另外,如果我有多键哈希,在这种情况下哈希被'number'和'even'或'odd'索引,如果我做这样的事情:

foreach my $key (keys %hash)
{
print "First Key: $key\n";  #Outputs number
}
Run Code Online (Sandbox Code Playgroud)

然后我总是将"数字"作为输出权,我永远不会得到"偶数","奇数"作为输出,对吗?这只是为了知道良好的编码实践:)

这是完整的代码:

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";
}
Run Code Online (Sandbox Code Playgroud)

谢谢,新手

Kei*_*son 6

my %hash;
$hash{'number'}{'even'} = [24, 44, 38, 36];
$hash{'number'}{'odd'} = [23, 43, 37, 35];
Run Code Online (Sandbox Code Playgroud)

%hash是一个哈希,其键是strings('number'),其值是哈希引用.

foreach my $key (keys %hash{'number'})
{
   print "Key: $key\n";
}
Run Code Online (Sandbox Code Playgroud)

要引用一个值%hash,你要写$hash{'number'},而不是%hash{'number'}.

但是$hash{'number'}是哈希引用,而不是哈希.要引用它引用的哈希,您可以这样写:

%{$hash{'number'}}
Run Code Online (Sandbox Code Playgroud)

把这一切放在一起:

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";
}
Run Code Online (Sandbox Code Playgroud)

将产生此输出:

Key: even
Key: odd
Run Code Online (Sandbox Code Playgroud)

(可能不是那个顺序).

  • 如果你使用的是5.14或更高版本,键,值,每个,push,pop,slice,shift和unshift现在可以在引用上运行.这意味着`keys%{$ hash {k}}`可以重写为`keys $ hash {k}`.麾! (2认同)