in reply to appending and array into last element of an array?

You can't store an array in an array, but you can store a reference to one.
# Saves a reference to the existing array. push(@arrayA, \@arrayB);
# Creates a new (anon) array and saves a reference to it. push(@arrayA, [ @arrayB ]);

Replies are listed 'Best First'.
Re^2: appending and array into last element of an array?
by mdunnbass (Monk) on Oct 11, 2006 at 16:30 UTC
    OK. that sounds good so far, but if I'm doing this in a looping context, and the next time around the loop, the values of @arrayB change, won't that change all of the references as well?

    Also, how could I save the anon array in your second example? setting something equal to the push gives the length of the new array, right? Could I just do

    push(@arrayA, [ @arrayB ]); @new_array = @_;

    would that work?

    And thanks for the quick reply.
    Matt

      OK. that sounds good so far, but if I'm doing this in a looping context, and the next time around the loop, the values of @arrayB change, won't that change all of the references as well?

      It depends on where @arrayB is declared.

      my @arrayA; my @arrayB; while (...) { @arrayB = ...; push(@arrayA, \@arrayB); # XXX }
      my @arrayA; my @arrayB; while (...) { @arrayB = ...; push(@arrayA, [ @arrayB ]); # Ok }
      my @arrayA; while (...) { my @arrayB = ...; push(@arrayA, \@arrayB); # Ok }
      my @arrayA; while (...) { my @arrayB = ...; push(@arrayA, [ @arrayB ]); # Needlessly creating 3rd array. }

      Also, how could I save the anon array in your second example?

      What does "save" mean? Copy? You already have a copy of the array in @arrayB.