问题
I'm trying to dynamically create an associative array whose values are arrays. My current attempt is as follows but I'm not sure if it is correct or efficent.
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;
}
}
回答1:
pretty sure this works (can't test right now)
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;
}
(using unshift instead of push will put the new entry on the other side of the other entries)
来源:https://stackoverflow.com/questions/17713028/dynamically-creating-an-associative-array-of-arrays