in reply to accessing element of array of arrays

Assignment between array elements should work just as you described, so I think there's more going on than you think. Can you post a brief but runnable demonstration of the effect you're seeing?

Unless I state otherwise, all my code runs with strict and warnings
  • Comment on Re: accessing element of array of arrays

Replies are listed 'Best First'.
Re^2: accessing element of array of arrays
by perlqs (Initiate) on Jul 06, 2008 at 04:11 UTC
    Ok:
    #!/usr/bin/perl use strict; use warnings; my @AoA1 = ([1, 'a'], [2, 'b']); my @AoA2; push @AoA2, @AoA1; $AoA2[0][0] = $AoA1[0][0]; print "$AoA1[0][0], $AoA2[0][0]\n"; $AoA2[0][0] ++; print "$AoA1[0][0], $AoA2[0][0]\n";
    Notice that when $AoA2[0][0] is augmented, $AoA1[0][0] is as well. The desired output would be:
    1, 1 2, 1
    instead of
    1, 1 2, 2
    .
      In Perl, an array of arrays is really an array of references to arrays. You can see that by printing @AoA1:
      say @AoA1; # ARRAY(0x606df0)ARRAY(0x621e70)
      When you push @AoA2, @AoA1; you're pushing the same references on to @AoA2:
      say @AoA2; # ARRAY(0x606df0)ARRAY(0x621e70)
      The hex numbers are the same, indicating the both refer to the same area of memory.

      So, to answer your original question, changing one of the array elements, will also change the corresponding element in the other array. To get round that, you could use

      • the freeze & thaw functions from the core module Storable
      • the CPAN module Clone
      • some Perl
      use Clone 'clone'; my @AoA3 = @{ clone( \@AoA1 ) }; say @AoA3; # ARRAY(0x7c46c0)ARRAY(0x7c4720) use Storable qw/freeze thaw/; my @AoA4 = @{ thaw( freeze( \@AoA1 ) ) }; say @AoA4; # ARRAY(0x7095c8)ARRAY(0x709718) my @AoA5 = map { [ @$_ ] } @AoA1; say @AoA5; # ARRAY(0x67ff58)ARRAY(0x7e8468)
      Storable and Clone will work with any data structure but the pure perl method will need to be tailored to each specific data structure.

      Unless I state otherwise, all my code runs with strict and warnings