Changing one array affects the other

4

490

I have a strange problem.
There is a template that I want to use for a few arrays.

But in one array I want to change one of the parameters in the
anonymous hash thats inside the array, but when I change the hash in
arrTwo then arrOne also changes.
Why is that!?

#Script begins
my @Template = (
{
name => "Person",
params => []
},
{
name => "Doggi",
params => []
}
);

@arrOne = @Template;


#Print array before changing the Other array
print $arrOne[1]->{name} . "\n";

my @arrTwo = @Template;
$arrTwo[1]->{params} = [['John','doe']];
$arrTwo[1]->{name} = "This does not work well!!!!";

#Print array after changing the Other array
print $arrOne[1]->{name} . "\n";

#Script ends

The script returns:
Doggi
This does not work well!!!!

instead of Doggi twice.

Thanks!
 
M

Mumia W.

I have a strange problem.
There is a template that I want to use for a few arrays.

But in one array I want to change one of the parameters in the
anonymous hash thats inside the array, but when I change the hash in
arrTwo then arrOne also changes.
Why is that!?

#Script begins
my @Template = (
{
name => "Person",
params => []
},
{
name => "Doggi",
params => []
}
);

@arrOne = @Template;


#Print array before changing the Other array
print $arrOne[1]->{name} . "\n";

my @arrTwo = @Template;
$arrTwo[1]->{params} = [['John','doe']];
$arrTwo[1]->{name} = "This does not work well!!!!";

#Print array after changing the Other array
print $arrOne[1]->{name} . "\n";

#Script ends

The script returns:
Doggi
This does not work well!!!!

instead of Doggi twice.

Thanks!

It's because @arrOne contains references to the hashes in @Template; the
elements of @arrOne and the elements of @Template both refer to the same
hashes.

What you want to do is to create a "deep copy" (or clone) of the @Template:

use Storable qw(dclone);
my @arrOne = @{dclone(\@Template)};

Read about references and cloning:
perldoc perlref
perldoc Storable

I hope this helps.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,483
Members
44,901
Latest member
Noble71S45

Latest Threads

Top