0

using Perl I am trying to push the elements of an array to another array, and not the whole array. But I'm not getting my goal.

I tried this:

push @tmp_entities_all, @tmp_entities;

But I got the whole small array as an element in the bigger array.

Then I tried it with a loop:

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

But the same results, the whole @tmp_entities appears as an element, and that what I dont want.

I need one dimension in the array and not array of arrays!! Should I cast something before pushing? or what is the problem?

Thanx a lot.

7
  • Both methods should work. Try to dump your @tmp_entities_all after push by use Data::Dumper; print Dumper(\@tmp_entities_all); and include the output in your question. Commented Apr 11, 2014 at 9:12
  • [ { 'type' => 'month', 'attr' => { } } ], [ { 'type' => 'day', 'attr' => { } }, { 'type' => 'day', 'attr' => { } } ],... Commented Apr 11, 2014 at 9:18
  • try this oneliner perl -e '@a=(1,2,3,4); @b=(5,6,7,8); push @a,@b; print "@a\n";' as you can see what you are asking should work Commented Apr 11, 2014 at 9:19
  • The loop is working now: I've changed it to @$_ instead of simply $_.. But the other method is more effective and should somehow work.. Commented Apr 11, 2014 at 9:20
  • 1
    Your array @tmp_entities contains an arrayreference, that is holding the elements. Perhaps you defined your array like that @tmp_entities = [ 1, 2, 3] ... but you should do @tmp_entities = ( 1, 2, 3 ) ... This is, why your loop works with @$_ and your push in the first try push the arrays "as one element" ... Commented Apr 11, 2014 at 9:26

1 Answer 1

1

Out of your comments, its obvious, that @tmp_entities contains only one element, that is an array reference to the elements that you expected to be elements of @tmp_entities.

So you perhaps declared your array with an array refence instead of using a set of elements.

The line

push @tmp_entities_all, @tmp_entities;

definitly works for a normal array.

In your case, your could try ...

push @tmp_entities_all, $tmp_entities[0];

or you simply try to initialize your array with its value like

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

instead of

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

I know, that this is the case, because this is why your for-loop sample works with @$_ ;D (it is equivalent to push @tmp_entities_all, $tmp_entities[0]; in this situation).

Sign up to request clarification or add additional context in comments.

1 Comment

another way could be to use: my @tmp_entities = qw/1 2 3/;.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.