Beefy Boxes and Bandwidth Generously Provided by pair Networks RobOMonk
We don't bite newbies here... much
 
PerlMonks  

Copying multi-dimensional array

by rpike (Scribe)
on Apr 21, 2011 at 14:24 UTC ( #900626=perlquestion: print w/ replies, xml ) Need Help??
rpike has asked for the wisdom of the Perl Monks concerning the following question:

I have an array such as this :
$Array1[0][0] = 10; $Array1[0][1] = 15; $Array1[1][0] = 20; $Array1[1][1] = 30; .... @Array2 = @Array1; # Loop through @Array1 and make changes to it. After loop I want to ma +ke reference to initial values that were stored in Array1 through use + of Array2.
How can I copy Array1 (2 dimensional array) and use that copy after the loop the exact same way as I would trying to access items from the newly updated Array1 array? I tried @Array2 = @Array1 but any changes to Array1 are reflected in Array2. Should I use Storable::dclone? What would be the simpliest steps needed to copy the array and afterwards reference the exact same way as the modified Array1? Thanks in advance for any help.

Comment on Copying multi-dimensional array
Download Code
Re: Copying multi-dimensional array
by ikegami (Pope) on Apr 21, 2011 at 14:24 UTC
Re: Copying multi-dimensional array
by wind (Priest) on Apr 21, 2011 at 14:43 UTC

    Yep, dclone is about as simple as you're going to find.

    use Storable qw(dclone); use Data::Dumper; use strict; use warnings; my @Array1 = ([10,15],[20,30]); my $Array2 = dclone(\@Array1); $Array1[0][1] = 71; # Does change translate? print Dumper($Array2); # Nope
      Thanks for the info guys. I added the following as well.
      my @Array2 = @{ dclone(\@Array1) };
Re: Copying multi-dimensional array
by SimonClinch (Chaplain) on Apr 21, 2011 at 14:55 UTC
    YADA (Yet Another Dumper Approach):
    use Data::Dumper; my $VAR1; # must be this variable name # ... populate @array1 here ... eval Dumper( \@array1 ); my @array2 = @$VAR1; # ... now array2 is copied at all levels into its own storage at all l +evels

    One world, one people

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://900626]
Approved by ikegami
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others romping around the Monastery: (10)
As of 2014-04-17 07:21 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    April first is:







    Results (440 votes), past polls