Dynamically creating an associative array of arrays

拈花ヽ惹草 提交于 2021-01-27 11:38:07

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!