2014-09-19 44 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標記中。

相關問題