Perl:为单个键打印具有多个值的哈希
我对一个键使用了多个值的散列。如何在散列中独立打印多个密钥值Perl:为单个键打印具有多个值的哈希,perl,hash,reference,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>&
# 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} };
为@{$hash{$key}打印“$\”;
它将循环数组引用中的每个项,并将它们包装在
td
标记中。使用另一个foreach
循环获取值。或者使用map
将它们包装在…
中并打印结果。