【问题标题】:Pushing array as an item to another array - not creating multidimensional array将数组作为项目推送到另一个数组 - 不创建多维数组
【发布时间】:2012-12-10 16:47:14
【问题描述】:

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

【问题讨论】:

    标签: arrays perl


    【解决方案1】:

    不完全确定为什么会这样,但确实如此......

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

    我的回答中详细解释了最后一个 sn-p。

    【讨论】:

      【解决方案2】:

      首先是括号

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-05-24
        • 1970-01-01
        • 2022-12-07
        • 2016-11-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-06-13
        相关资源
        最近更新 更多