in reply to Re: hash ref mind blow
in thread hash ref mind blow
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Shallow vs deep copy (Was Re^3: hash ref mind blow)
by ikegami (Patriarch) on Sep 24, 2008 at 21:22 UTC | |
You might think of
as a single hash, but that's not the case. There are three:
When you do %copy = %hash (which you wrote as %copy = %{ \%hash }), you are copying the keys and values of %hash. So what are the keys and values of %hash?
That's all that's copied, nothing more. It will not make a copy of the referenced value and make a new reference to it. It simply copies the references. You end up with
What you want is to do is to copy referenced values as well, and to do recursively, so that you end up with the following:
That's called a "deep copy" because it copies every level of the data structure. In contrast, a simple assignment is called a "shallow copy" because it only copies the immediate value (scalar/hash/array/...). | [reply] [d/l] [select] |
by Anonymous Monk on Sep 25, 2008 at 15:38 UTC | |
It's coincidental, but everytime I used it as reference passed to subs, I added subkeys and everything worked as an alias. To my surprise, when I added a root key to %copy and it didn't change %hash my world came tumbling down. So it's back to $$copy->{key} stuff, as
Looks so unscoped to my personal perl taste. And Data::Alias will not cpan into my Strawberry perl, complaining about requiring perl 5.8.9 on Win32... BTW ikegami, wow! Now... I want to know what package does those hash textgraphs you posted. Cos Data::Dumper doesn't get even close to that kind of representation! | [reply] [d/l] [select] |
by ikegami (Patriarch) on Sep 25, 2008 at 21:40 UTC | |
should be
Or if you prefer,
What's the point of localizing %copy? Depending on whether you do it before or after the aliasing, you either localize a variable you never use, or you localize %hash. But you do modify *copy, so you should localize that.
Notepad. | [reply] [d/l] [select] |