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>".@{$hash{$key}}."</td>";
}

*电流输出:*

 Category  Value1         Value2
 fruits    apple mango
 vegs      Potato Onion

*所需输出:*

 Category  Value1   Value2
 fruits    apple     mango
 vegs      Potato    Onion

尝试用替换循环的第二行

print "<td>$_</td>" for @{ $hash{$key} };

它将循环遍历数组引用中的每个项,并将它们封装在td标记中。

最新更新