2014-09-19 45 views
1

我有一个具有多个值的散列到键。如何独立地在散列中打印多个键值?Perl:为单个密钥打印具有多个值的散列

# 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>"[email protected]{$hash{$key}}."</td>"; 
} 

*电流输出:*

Category Value1   Value2 
fruits apple mango 
vegs  Potato Onion 

*所需的输出:*

Category Value1 Value2 
fruits apple  mango 
vegs  Potato Onion 
+0

对这些值使用另一个'foreach'循环。或使用'map'将它们包装在'​​...'中并打印出结果。 – Barmar 2014-09-19 18:20:16

回答

2

尝试用

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

它将循环访问数组引用中的每个项目并将它们包装在td标记中。

相关问题