http://qs321.pair.com?node_id=814548


in reply to Data Dumper Question

Others have pointed out how to make the behaviour conform to your expectations; but I wanted to point out that ‘fix’ may not be the right term, since Data::Dumper is correctly indicating to you that your $hashref->{test1} and $hashref->{test2} are not just 2 references to similar hashes, but literally the same hashref. You can demonstrate this to yourself:

$hashref->{test1}{temp}[0] = 456; print $hashref->{test2}{temp}[0]; # => 456
This is the classical problem of deep versus shallow copies.

The reason that you don't get the desired behaviour when you eval the output of Dumper is that the eval happens “all at once”—when the ‘inner’ reference to $VAR1->{test1}{temp}[0] is being evaluated, $VAR1 doesn't yet have the value that it will have when the eval completes, so all you're doing is auto-vivifying it as a reference to a hash-of-hashes-of-arrays. Accessing the 0th entry of that innermost array makes sure that it exists, but doesn't assign it a value, so it comes out undef. The documentation for Data::Dumper warns of this (but, in my opinion, not very clearly), and mentions the solution that ikegami already gave:

The default output of self-referential structures can be evaled, but the nested references to $VARn will be undefined, since a recursive structure cannot be constructed using one Perl statement. You should set the Purity flag to 1 to get additional statements that will correctly fill in these references. Moreover, if evaled when strictures are in effect, you need to ensure that any variables it accesses are previously declared.

Replies are listed 'Best First'.
Re^2: Data Dumper Question
by clintonm9 (Sexton) on Dec 28, 2009 at 14:13 UTC
    Thanks for all your help! this did fix my problem!