rakeshrocks has asked for the wisdom of the Perl Monks concerning the following question:
Similar to ENABLE key, I have many other keys on which I am doing the operation and at end, I am attaching back the value of %newhashif ($padinstance =~/^\s*(\w+)\[\s*(\d+)\s*\:\s*(\d+)\s*\]\s*$/) { #Check and modify simultaneously my $padword = $1; my $msb = $2; my $lsb = $3; my %hashcopy = %{$topxls_hash_ref->{$hier}->{$padinstance}}; for (my $counter = 0; $counter <= $msb - $lsb; $counter ++) { my %newhash = %hashcopy; foreach my $chk_key (keys (%hashcopy)) { if ($chk_key eq "MODE") { ## For each mode check type and do action foreach my $mode (keys (%{$hashcopy{MODE}})) { if ($hashcopy{MODE}->{$mode}->{TYPE} eq "O") { foreach my $chk_mode_key (keys (%{$hashcopy{MODE} +->{$mode}})) { if ($chk_mode_key eq "ENABLES") { foreach my $enable_sig (@{$hashcopy{MODE}->{ +$mode}->{ENABLES}}) { if ($enable_sig =~/\w+/) { print Dumper(\%hashcopy); if (defined ($hashcopy{MODE}->{$mode}- +>{"EN\@$enable_sig"}) && $hashcopy{MODE}->{$mode}->{"EN\@$enable_sig" +} =~/\w+/) { my $array_index = 0; foreach my $enable_sig_iter (@{$ha +shcopy{MODE}->{$mode}->{"EN\@$enable_sig"}}) { print "In mode for $mode for ENABLES $enable +_sig_iter\n"; if ($enable_sig_iter =~/^(\s*\w+ +)\s*\[\s*(\d+)\s*\:\s*(\d+)\s*\]/) { my $prefix_word = $1; my $local_msb = $2; my $local_lsb = $3; if ($local_msb - $local_lsb = += $msb - $lsb) { my $token = $local_lsb + $ +counter; my $newsignal = "$prefix_w +ord\[$token\]"; $newhash{MODE}->{$mode}->{ +"EN\@$enable_sig"}->[$array_index] = $newsignal; } else { + return -1; } } $array_index ++; } } } }
however, after first iteration, modification in %newhash also modifies %hashcopy. I am not able to understand the reason behind such behaviour in nested hashes. Please help! Please let me know, where I am going wrong. While searching after posting, I came across that this is more to do with shallow copy. I need to make a deep copy.$topxls_hash_ref->{$hier}->{$padinstance_new} =\%newhash;
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Hash value, containing a reference to some value of hash, not the intended behaviour.
by cdarke (Prior) on Mar 14, 2011 at 11:34 UTC | |
|
Re: Hash value, containing a reference to some value of hash, not the intended behaviour.
by Anonymous Monk on Mar 14, 2011 at 11:00 UTC | |
by rakeshrocks (Initiate) on Mar 14, 2011 at 11:24 UTC |