gpt4 book ai didi

arrays - 动态创建数组的关联数组

转载 作者:行者123 更新时间:2023-12-01 15:29:38 25 4
gpt4 key购买 nike

我正在尝试动态创建一个值为数组的关联数组。我目前的尝试如下,但我不确定它是否正确或有效。

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;
}
}

最佳答案

非常确定这有效(现在无法测试)

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 会将新条目放在其他条目的另一边)

关于arrays - 动态创建数组的关联数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17713028/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com