Mark Lyons
Mark Lyons

Reputation: 1422

Pushing array as an item to another array - not creating multidimensional array

I have an array, @allinfogoals and I want to make this a multidimensional array. In attempt to accomplish this, I'm trying to push an array as an item like so:

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

Where those items in the array parenthesis are all individual strings I have beforehand. However, if I reference $allinfogoals[0], I get the value of $tempcomponents[0] and if I try $allinfogoals[0][0] I get:

Can't use string ("val of $tempcomponents[0]") as an ARRAY ref while "strict refs" in use

How can I add these arrays to @allinfogoals to make it a multidimensional array?

Upvotes: 6

Views: 11568

Answers (2)

ikegami
ikegami

Reputation: 385917

First of all, the parens in

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

do nothing at all. It's just a weird way of writing

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

Parens change precedence; they don't create list or arrays.


Now on to your question. There's no such thing as a 2d array in Perl, and arrays can only hold scalars. The solution is to create an array of references to other arrays. That's why

$allinfogoals[0][0]

is short for

$allinfogoals[0]->[0]
   aka
${ $allinfogoals[0] }[0]

As such, you need to store your values in an array and put a reference to that array in the top-level array.

my @tmp = ( @tempcomponents[0,1], $singlehometeam );
push @allinfogoals, \@tmp;

But Perl provides an operator that simplifies that for you.

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

Upvotes: 16

Mark Lyons
Mark Lyons

Reputation: 1422

Not exactly sure why this works, but it does...

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

Needed to create an iterator, $i to do this.


According to @ikegami, what follows is the reason.

That only works if $allinfogoals[$i] isn't defined, when it's a weird way of writing

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

which utilises autovivification to do the equivalent of

$allinfogoals[$i] = [ $tempcomponents[0], $tempcomponents[1], $singlehometeam ];

which can be achieved without $i using

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

This last snippet is explained in detail in my answer.

Upvotes: 3

Related Questions