我希望这段小片段显示swatkats,popeye,复仇者阵列中的内容但是我无法打印它
%HoA = (
swatkats => [ "Tbone", "Razer" ],
popeye => [ "Olive", "bluto", "pope" ],
avengers => [ "ironman", "hulk", "Blackwidow","cap"]);
@arr=keys%HoA;
print "$arr[0]\n";
print "@arr[1]\n";
print "@arr[2]\n";
输出是:
swatkats
大力水手
复仇者
但预期输出:
Tbone Razer 橄榄bluto教皇 铁人绿巨人blackwidow帽
我在这里做错了什么?
Ps:如何在上面的代码片段中添加另一个数组进行哈希。
答案 0 :(得分:2)
您要查找的输出将生成:
%HoA = (
swatkats => [ "Tbone", "Razer" ],
popeye => [ "Olive", "bluto", "pope" ],
avengers => [ "ironman", "hulk", "Blackwidow", "cap"]);
@arr = keys %HoA;
print join(' ', @{$HoA{$arr[0]}}). "\n";
print join(' ', @{$HoA{$arr[1]}}). "\n";
print join(' ', @{$HoA{$arr[2]}}). "\n";
通过以下方式添加另一个条目:
$HoA{'new entry'} = [ 1, 2 , 4 ];
HTH 乔治
答案 1 :(得分:1)
您获得的输出是因为您使用了keys
关键字来迭代哈希的键。您可以使用values
关键字来迭代值:
my %HoA = (
swatkats => [ "Tbone", "Razer" ],
popeye => [ "Olive", "bluto", "pope" ],
avengers => [ "ironman", "hulk", "Blackwidow","cap"]
);
foreach my $value (values %HoA)
{
print join(' ', @$value), "\n";
}
输出:
ironman hulk Blackwidow cap
Olive bluto pope
Tbone Razer