Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hallo perly monks,

I'm trying to do something like this;

push(@array,@stuff) push(@array,@morestuff) ... ...
but I end up with
@array=(foo,bar,foo,bar)
instead of
@array=([foo,bar],[foo,bar])
Does anyone know how to stop my arrays getting squashed?

...Also, I'm going to need to push elements onto the end of arrays in arrays. My thgouhts on this so far have been along the lines of;

push(@{$array[$aidx]},$value);
will that work?

Thanks muchly,

Matt

update (broquaint): added <code> tags

Replies are listed 'Best First'.
Re: pushing into arrays of arrays
by Tomte (Priest) on Mar 05, 2004 at 11:52 UTC

    push references:

    push(@array,\@stuff); push(@array,\@morestuff);
    arrays and hashes can only hold scalar values; luckily references are scalar values ;-)

    Update: Maybe it helps to read over perldata and perlref again...

    regards,
    tomte


    Hlade's Law:

    If you have a difficult task, give it to a lazy person --
    they will find an easier way to do it.

Re: pushing into arrays of arrays
by xdg (Monsignor) on Mar 05, 2004 at 12:15 UTC

    Previous post about using references was right on. As a side note, though, if you're pushing an array that you reuse in a loop, you'll want to create a new, anonymous array reference each time through. E.g.

    while ( @array = somefunc() ) { push( @aoa, [ @array ] ); }

    To your second question, yes, that should work.

    -xdg

    Code posted by xdg on PerlMonks is public domain. It has no warranties, express or implied. Posted code may not have been tested. Use at your own risk.

      Thanks for the replies;

      I have a problem with references in that I was specifically hoping to create a copy of the array. The code works a bit like this;
      loop loop calculate @values end loop push @values into @sets for use later end loop
        Just read the post from xdg above your post again. He just pointed out, that you could use copies in such a case using

        push @array, [ @localarray ]

        instead of

        push @array, \@localarray