http://www.perlmonks.org?node_id=1032283


in reply to help with references

It might help to “clear your mind and” consider this:   there is no such thing as a hash of arrays.   Or an array of hashes, or an array of arrays, or anything else.   All of Perl’s multi-element data structures (lists, arrays, hashes) are one-dimensional.

The “secret sauce” is, of course, a reference, which is a single thing.   Any scalar-variable, or any bucket in a list, array, or hash, can therefore contain a “reference” just as easily as it could contain a “number” or a “string” or any other single-thing.   But a reference can refer to ... anything at all.   It can refer to a scalar, or any of the multi-element data structures, or anything else.   Furthermore, all of the things that it can refer-to have a “reference count,” which tracks how many references to them currently exist, so that nothing will be garbage-collected while any (non-weakened) references to it remain.   You can create very complex data-structures with impunity and never worry about a C/C++ style “segfault.”

But you do have to know what is going on.   Perl is very much a “DWIM = Do What I Mean” language.   It has several syntactic shortcuts ... which can indeed be very deceptive if you do not fully understand how Perl actually interprets them.   Unlike many programming tools, there isn’t a static indication in the source-code that a reference is being used at any particular point:   many determinations are made by the Perl interpreter at run-time, as it tries to DWYM.   So, you look at the source-code (which is syntactically valid), and don’t see the problem.

In your example, you created several references to ... the same chunk of data ... at several distinct places in your array.   To Perl, this has one thing being located at several places at one time ... that is to say, there are several references to the same data, each located in different spots.   Some of the various solutions that you’ve been shown involve making “deep copies,” that is to say, truly independent duplicates, of this data ... which might well be what you, in your mind’s eye, were intending to do all along.

Notice how Dumper is “references aware.”   It recognizes that the second element of the array is a reference to the identical block of data as the first, and it is designed to show you that.   In your code, $VAR1 (or whatever its name is ...) is a hash with two tags, and both tags contain a reference to the same piece of data.   Literally, to the same memory bytes, which therefore currently have a “reference count” at least equal to 2.   In Fortran parlance, they are EQUIVALENCEd.