enoch has asked for the wisdom of the Perl Monks concerning the following question:
Here is the code:
This ends up outputting:use Data::Dumper; my %h; # intial hash # put in some random values $h{'a'}{'1'} = 'z'; $h{'a'}{'2'} = 'y'; $h{'a'}{'3'} = 'x'; $h{'b'}{'4'} = 'w'; $h{'b'}{'5'} = 'u'; $h{'b'}{'6'} = 'v'; $h{'c'}{'7'} = 'r'; $h{'c'}{'8'} = 's'; $h{'c'}{'9'} = 't'; # make an assignment that I assume is by value my %tmpHash = %h; # make a change in the temp hash $tmpHash{'b'}{'6'} = 'j'; print Dumper(%h); print "\n\n\n"; print Dumper(%x);
$VAR1 = 'a';
$VAR2 = {
1 => 'z',
2 => 'y',
3 => 'x'
};
$VAR3 = 'b';
$VAR4 = {
4 => 'w',
5 => 'u',
6 => 'j'
};
$VAR5 = 'c';
$VAR6 = {
8 => 's',
9 => 't',
7 => 'r'
};
$VAR1 = 'a';
$VAR2 = {
1 => 'z',
2 => 'y',
3 => 'x'
};
$VAR3 = 'b';
$VAR4 = {
4 => 'w',
5 => 'u',
6 => 'j'
};
$VAR5 = 'c';
$VAR6 = {
8 => 's',
9 => 't',
7 => 'r'
};
As you can see, both hashes are changed. That surprised me. So, I am wondering how do you copy a hash by value. Is a foreach loop the only way to do it?
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Assigning Hash To Another Hash References Same Hash
by Masem (Monsignor) on Nov 16, 2001 at 01:24 UTC | |
|
Re: Assigning Hash To Another Hash References Same Hash
by davorg (Chancellor) on Nov 16, 2001 at 13:59 UTC | |
|
Re: Assigning Hash To Another Hash References Same Hash
by chipmunk (Parson) on Nov 16, 2001 at 07:34 UTC |