gpt4 book ai didi

arrays - 如何在 Perl 中创建二维数组?

转载 作者:行者123 更新时间:2023-12-04 01:29:54 26 4
gpt4 key购买 nike

我正在尝试在 Perl 中创建一个二维数组

我的代码:

my @wordsList=();
my @words=();

for ($id=0; $id<=@language.length; $id++)
{

my $eng = $db->selectall_arrayref("select word from words
left outer join language
on words.languageId = language.languageId
where words.languageId = $id
;");


foreach $eng(@$eng)
{
my($word) = @$eng;
$ref_to_Array->[$id][$word] = @words($id,$word);

}
return $words($id, $word);
}

$wordsList= NextWords();
print $wordsList;

它返回非..因为我想返回二维数组。

更新

我仍然很困惑,因为当我执行查询时,它给了我一个单词列表,例如:
select word from words where language_id = 1 
(1=english, 2 - chinese, 3 - french)

我正在通过语言使用 for 循环,以便从数据库中获取所有单词

问题是我想循环并希望将数组自动添加到二维数组中。

最佳答案

地点 use warnings; use strict;在您编写的每个程序的顶部。这两个 pragma 将为您捕获许多错误。

您不能使用 (...) 访问数组后缀。该构造用于调用函数 mysub(...)$mysubref->(...) .要访问数组元素,请使用后缀 [ index ] .而在 Perl 中,多维数组需要一对 [...]对于每个级别。这是因为二维数组只是一个数组,其中每个元素也是一个数组。

my @array = ([1, 2, 3], [4, 5, 6], [7, 8, 9]);

my $top_left = $array[0][0]; # 1
my $bottom_right = $array[2][2]; # 9

print "@$_\n" for @array;
1 2 34 5 67 8 9

You can learn more about Perl's data structures and the rest of Perl at perldoc.perl.org. Here are a few direct links:

Finally, @language.length does not do what you think it does. It is taking @language in scalar context, which is its length as a number and then concatenating it with length($_). The resulting expression is something like (scalar @language) . length($_). Since the <= operator imposes scalar context on its arguments, you could simply write $id <= @language. However, Perl provides you with a more natural way of writing this type of loop:

for my $id (0 .. @language) {...}

或者

对于我的 $id (0 .. $#language) {...}
如果你是真的意思 $id < @language$language[scalar @language]是数组末尾的一个元素。

关于arrays - 如何在 Perl 中创建二维数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5024183/

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