将数组作为项推入另一个数组 - 不创建多维数组

6

我有一个数组@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中,使其成为一个多维数组?

2个回答

16

首先,在括号中

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

什么也不用做。这只是一种奇怪的写作方式。

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

括号改变优先级;它们不创建列表或数组。


现在回答你的问题。在 Perl 中没有 2D 数组,而且数组只能容纳标量。解决方法是创建一个指向其他数组的引用数组。这就是为什么

$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 ];

3

不太确定为什么这样做有效,但它确实有效...

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

需要创建一个迭代器,$i 用来实现此功能。


根据 @ikegami 的说法,原因如下:

只有在未定义 $allinfogoals[$i] 时才能起作用,否则这种写法很奇怪。

@{$allinfogoals[$i]} = ( $tempcomponents[0], $tempcomponents[1], $singlehometeam );

使用自动初始化技术来实现相当于...的操作。
$allinfogoals[$i] = [ $tempcomponents[0], $tempcomponents[1], $singlehometeam ];

可以在不使用$i的情况下实现

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

这个代码片段在我的答案中详细解释。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接