2012-02-18 107 views
3

多加密哈希我有我索引这样一个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"; 
} 

感谢, 新手

回答

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

而且,为了学术上的兴趣,这里有更多关于哈希切片的信息,这是原始代码意外做的事情:http://perldoc.perl.org/perldata.html#Slices – fennec 2012-02-18 01:39:21

+0

OMG ...就是这样!我在想整个名字是一个关键!感谢您的详细解释。它真的帮助:) – Richeek 2012-02-18 01:39:26

+2

如果您使用5.14或更高版本,现在可以在引用上使用键,值,每个按钮,弹出,切片,移位和不移位功能。这意味着'keys%{$ hash {k}}'可以被重写为'keys $ hash {k}'。麾! – kbenson 2012-02-18 02:03:27

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"; 
    } 
} 
+0

是的,它的工作!非常感谢你。但是,加入花括号的动机是什么?我的意思是'键%{$ hash {'number'}}可以工作,但'键%hash {'number'}'没有,为什么? – Richeek 2012-02-18 01:36:38

+0

注意你自己的例子中的差异 - 在你传递给子程序的第二个例子中,这正是你正在做的。在第一个你不是。没有额外的大括号,它实际上并不是一个散列。 – si28719e 2012-02-18 01:39:46