Perl:打印具有单个键的多个值的哈希

时间:2014-09-19 18:17:32

标签: perl hash reference

我对一个键有多个值哈希。如何独立地在哈希中打印多个键值?

# HASH with multiple values for each key
my %hash = ( "fruits" => [ "apple" , "mango" ], "vegs" => ["Potato" , "Onion"]);

# SET UP THE TABLE
print "<table border='1'>";
print "<th>Category</th><th>value1</th><th>value2</th>";    

#Print key and values in hash in tabular format
foreach $key (sort keys %hash) {
    print "<tr><td>".$key."</td>";
    print "<td>".@{$hash{$key}}."</td>";
}

*当前输出:*

 Category  Value1         Value2
 fruits    apple mango
 vegs      Potato Onion

*所需输出:*

 Category  Value1   Value2
 fruits    apple     mango
 vegs      Potato    Onion

1 个答案:

答案 0 :(得分:2)

尝试用

替换循环的第二行
print "<td>$_</td>" for @{ $hash{$key} };

将遍历数组引用中的每个项目并将它们包装在td标记中。