【问题标题】:push ELEMENTS of array to an array using Perl使用 Perl 将数组的元素推送到数组
【发布时间】:2014-04-11 17:33:10
【问题描述】:

使用 Perl 我试图将一个数组的元素推送到另一个数组,而不是整个数组。但我没有达到我的目标。

我试过这个:

push @tmp_entities_all, @tmp_entities;

但我将整个小数组作为更大数组中的一个元素。

然后我用循环试了一下:

for (@tmp_entities) {push @tmp_entities_all, $_;}

但同样的结果,整个@tmp_entities 显示为一个元素,这是我不想要的。

我需要数组中的一维而不是数组数组!我应该在推动之前施放东西吗?或者是什么问题?

非常感谢。

【问题讨论】:

  • 这两种方法都应该有效。尝试在push 之后通过use Data::Dumper; print Dumper(\@tmp_entities_all); 转储您的@tmp_entities_all,并将输出包含在您的问题中。
  • [ { 'type' => 'month', 'attr' => { } } ], [ { 'type' => 'day', 'attr' => { } }, { 'type' => 'day', 'attr' => { } } ],...
  • 试试这个 oneliner perl -e '@a=(1,2,3,4); @b=(5,6,7,8); push @a,@b; print "@a\n";',因为你可以看到你所要求的应该可以工作
  • 循环现在正在工作:我已将其更改为 @$_ 而不是简单的 $_.. 但另一种方法更有效,并且应该以某种方式工作..
  • 您的数组@tmp_entities 包含一个数组引用,它保存着元素。也许您像 @tmp_entities = [ 1, 2, 3] 那样定义了您的数组 ...但您应该这样做 @tmp_entities = ( 1, 2, 3 ) .. . 这就是为什么您的循环与 @$_ 一起使用并且您在第一次尝试中将数组“作为一个元素”推送...

标签: arrays perl push


【解决方案1】:

在您的 cmets 中,很明显,@tmp_entities 仅包含一个元素,即对您希望成为 @tmp_entities 元素的元素的数组引用。

所以您可能使用数组引用而不是使用一组元素来声明您的数组。

线

push @tmp_entities_all, @tmp_entities;

绝对适用于普通数组。

在你的情况下,你可以尝试......

push @tmp_entities_all, $tmp_entities[0];

或者你只是尝试用它的值来初始化你的数组

my @tmp_entities = ( 1, 2, 3 ); # initialize array with 3 elements of type int

而不是

my @tmp_entities = [ 1, 2, 3 ]; # initialize array with 1 element that is an array reference with 3 elements of type int

我知道,情况就是这样,因为这就是为什么你的 for 循环示例与 @$_ ;D 一起使用的原因(在这种情况下它等同于 push @tmp_entities_all, $tmp_entities[0];)。

【讨论】:

  • 是的,如此真实..thanx all.. :))))
  • 另一种方法是使用:my @tmp_entities = qw/1 2 3/;.
猜你喜欢
  • 2012-07-10
  • 2014-04-16
  • 2013-01-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-28
  • 2018-09-19
相关资源
最近更新 更多