arrays - 将数组作为项目推送到另一个数组 - 不创建多维数组

标签 arrays perl

我有一个数组,@allinfogoals我想把它变成一个多维数组。为了实现这一点,我试图将一个数组作为一个项目推送,如下所示:

push @allinfogoals, ($tempcomponents[0], $tempcomponents[1], $singlehometeam);

数组括号中的那些项目都是我事先拥有的单个字符串。但是,如果我引用 $allinfogoals[0] ,我得到了 $tempcomponents[0] 的值如果我尝试 $allinfogoals[0][0]我得到:

Can't use string ("val of $tempcomponents[0]") as an ARRAY ref while "strict refs" in use

如何将这些数组添加到 @allinfogoals使它成为一个多维数组?

最佳答案

首先,括号中的

push @allinfogoals, ($tempcomponents[0], $tempcomponents[1], $singlehometeam);

什么都不做。这只是一种奇怪的写作方式
push(@allinfogoals, $tempcomponents[0], $tempcomponents[1], $singlehometeam);

parent 更改优先级;他们不创建列表或数组。

现在回答你的问题。 Perl 中没有二维数组这样的东西,数组只能容纳标量。解决方案是创建一个对其他数组的引用的数组。这就是为什么
$allinfogoals[0][0]

是简称
$allinfogoals[0]->[0]
   aka
${ $allinfogoals[0] }[0]

因此,您需要将您的值存储在一个数组中,并将对该数组的引用放在顶级数组中。
my @tmp = ( @tempcomponents[0,1], $singlehometeam );
push @allinfogoals, \@tmp;

但是 Perl 提供了一个运算符来为您简化。
push @allinfogoals, [ @tempcomponents[0,1], $singlehometeam ];

关于arrays - 将数组作为项目推送到另一个数组 - 不创建多维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14018358/

相关文章:

perl - 为什么 Perl 认为 -1 是真的?

javascript - SumoSelect 没有选择数组中的所有值

c - 使用 sizeof 作为数组下标时的警告

部分数组的java for-each循环

javascript - 将 childNodes 转换为下划线数组的最佳方法

regex - 在perl中使用正则表达式检索两个字符串定界符之间的字符串

perl - Perl 中的词法范围和动态范围有什么区别?

javascript - 无法在React渲染中使用map函数

linux - 如何使用awk进行过滤(perl自动化)

MongoDB CPU 使用率高/读取时间长