我正在尝试动态创建一个值为数组的关联数组。我目前的尝试如下,但我不确定它是否正确或有效。
foreach $line (@lines) # read line from a text dictionary
{
chomp( $line );
my($word, $definition) = split(/\s/, $line, 2); #
$definition =~ s/^\s+|\s+$//g ; # trim leading and trailing whitespace
if( exists $dict{$word} )
{
@array = $dict{$word};
$len = scalar @array;
$dict{$word}[$len] = $definition;
}
else
{
$dict{$word}[0] = $definition;
}
}
答案 0 :(得分:2)
非常确定这是有效的(现在无法测试)
foreach $line (@lines) # read line from a text dictionary
{
chomp( $line );
my($word, $definition) = split(/\s/, $line, 2); #
$definition =~ s/^\s+|\s+$//g ; # trim leading and trailing whitespace
push @{$dict{$word}}, $definition;
}
(使用unshift而不是push会将新条目放在其他条目的另一侧)