2012-12-24 52 views
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使它成为一个多维数组?

回答

15

首先,在

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

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

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

Parens改变优先顺序;他们不创建列表或数组。


现在到你的问题。在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 ]; 
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 ]; 

This last snip宠物在我的答案中详细解释。

+3

这可以解释为什么这个工程... http://perldoc.perl。组织/ perlreftut.html – squiguy

相关问题