全部博文(1144)
分类: LINUX
2009-03-19 22:18:24
我们在遍历二维或多维的散列时, 可以采用递归的方法.
1. 首先查看每个value的值类型, 如HASH, ARRAY, 还是简单的标量
2. 如果value的值类型是HASH,则递归直到找到相应的ARRAY 或者标量
3. 如果value的值类型是ARRAY,则通过循环打印出各个元素
4. 如果value的值类型是标量,则直接打印
my %kids_of_wife;
$kids_of_wife{"Jacob"}{"John"} = {"Leah" => ["Reuben", "Simeon", "Levi", "Judah", "Issachar", "Zebulun"],
"Rachel" => ["Joseph", "Benjamin"],
"Bilhah" => ["Dan", "Naphtali"],
"Zilpah" => ["Gad", "Asher"],};
my @array = (1,2,3,4,5);
@{$kids_of_wife{"Jacob"}{"John"}{"Betty"}} = @array;
$kids_of_wife{"Jacob1"}{"John1"} = {"Leah1" => ["Reuben1", "Simeon1", "Levi1", "Judah1", "Issachar1", "Zebulun1"],
"Rachel1" => ["Joseph1", "Benjamin1"],
"Bilhah1" => ["Dan1", "Naphtali1"],
"Zilpah1" => ["Gad1", "Asher1"],};
my %a;
$a{m}{n}=1;
$a{m}{n2}=5;
$a{m}{n3}=2;
$a{m1}{n}=1;
$a{m1}{q}=8;
PrintHash(\%a, "");
PrintHash(\%kids_of_wife, $keyWord);
sub PrintHash
{
my ($hash, $keyWord) = @_;
if ($hash =~ /^HASH/)
{
while(my ($key,$value)=each(%$hash))
{
if ($value =~ /^HASH/)
{
$keyWord = $keyWord."$key\:\:";
PrintHash($value,$keyWord );
$keyWord = "";
}
elsif ($value =~ /^ARRAY/)
{
my @array = @{$value};
print "$keyWord$key => ";
foreach (@array)
{
print "$_ ";
}
}
else
{
print "$keyWord$key => $value\n";
}
print "\n";
}
}
}
Result:
m1::n => 1
m1::q => 8
m::n => 1
m::n2 => 5
m::n3 => 2
Jacob1::John1::Rachel1 => Joseph1 Benjamin1
Jacob1::John1::Leah1 => Reuben1 Simeon1 Levi1 Judah1 Issachar1 Zebulun1
Jacob1::John1::Zilpah1 => Gad1 Asher1
Jacob1::John1::Bilhah1 => Dan1 Naphtali1
Jacob::John::Zilpah => Gad Asher
Jacob::John::Bilhah => Dan Naphtali
Jacob::John::Leah => Reuben Simeon Levi Judah Issachar Zebulun
Jacob::John::Betty => 1 2 3 4 5
Jacob::John::Rachel => Joseph Benjamin