|Perl: the Markov chain saw|
O, the horrors of references and complex data structuresby DeusVult (Scribe)
|on Feb 06, 2001 at 01:28 UTC||Need Help??|
DeusVult has asked for the
wisdom of the Perl Monks concerning the following question:
I have an array of hashes. Well, technically it is an array of hash references, which AFAIK is the only way to construct an array of hashes in Perl. This array is declared globally. Let us call this array AoH.
I also have a globally declared hash, let us call it globHash.
My script jumps around from subroutine to subroutine. Each subroutine makes a few changes to globHash and then calls one or more (usually more) other subroutines which do the same. That is the reason that globHash is declared globally, because it is constantly being changed, re-changed, and changed again.
Eventually, I come to the end of one chain of subroutine calls. At the end of this chain, I push globHash onto AoH like this
Then, through the magic of the run-time stack, I back up to the beginning of this chain, and follow a different one until that chain, too, comes to an end, and I push the hash onto the array again. Lather, rinse, repeat as necessary (and it is necessary to do so many times).
When all is said and done, I find that I have only succeeded in pushing dozens of identical hashes onto the array. All of the array entries, no matter when they were pushed, have the same values as the last hash I pushed onto the array.
Obviously, references are more like pointers than I had imagined. Now that this has happened, I am not surprised that it has done so (how impressive of me, predicting events that have already occurred). The question remains, now that I know this happens, how do I stop it? If I was righting this in C++, I would do
So my question to you, O monks of wondrous knowledge, is this: is there some sort of delete/new equivalent in Perl (and I know that OO constructors are sometimes named new, but that isn't even remotely like what I'm talking about)? Can I get the hash to "reset" itself so that, when I take its reference a second time, it will be a different reference from when I took it the first time?
Some people drink from the fountain of knowledge, others just gargle.