Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask

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.

Replies are listed 'Best First'.
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 (Deacon) 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?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://900626]
Approved by ikegami
[marioroy]: Thank you Lady_Aleena. I've bookmarked the page.
[1nickt]: folks, would you say that 1.0 is an integer ?
[Lady_Aleena]: 1nickt, I wouldn't, but I'm not normal.
LanX aggrees, LA isn't normal ;-P
[Lady_Aleena]: LanX, thanks bunches.
[Lady_Aleena]: Rigth now I'm ranting in my head about an old subject.
[1nickt]: Hm, that is, how to prevent Perl from turning 1.0 into 1? I feel sure this must be an faq, but am reading perlnum and not finding the answer ...
[Lady_Aleena]: 1nickt, why does it matter in this case?
[1nickt]: Hm, perhaps this? "Operators which expect an integer force the argument into the integer format."

How do I use this? | Other CB clients
Other Users?
Others imbibing at the Monastery: (9)
As of 2017-05-24 18:29 GMT
Find Nodes?
    Voting Booth?