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

johnrcomeau has asked for the wisdom of the Perl Monks concerning the following question:

I'm trying to use the Data::Dumper module to save a hash of hash structure. Data::Dumper refers to an earlier part of the structure if it encounters a reference it has already printed. The problem is that when I try to read this structure back with the 'do' command, this self-referential part is not recognized. I thought that what I'm doing is a pretty common use of the Data::Dumper module, so perhaps there is an option to force every reference to be spelled out without self-references. But that really wouldn't be the same structure, right? The variable itself has the same reference in many locations, so the Data::Dumper string should have that too. I'm probably not describing the problem well. My example should clear things up.
my %element = (a => 1, b => 2); my %hash; $hash{key1}{key2} = $hash{key2}{key1} = \%element; warn Data::Dumper->Dump([\%hash], [qw(rh_saved_hash)]); my $file = 'saved.dat'; open SAVE, ">$file" or die "$file: $!\n"; print SAVE Data::Dumper->Dump([\%hash], [qw(rh_saved_hash)]); close SAVE; do $file; warn 'retrieved ', Dumper $::rh_saved_hash;
When I read back the hash with the 'do' command, the $hash{key1}{key2} part is undef. (When you run this, you might see $hash{key2}{key1} lost, depending on the order that Data::Dumper writes the keys.) Is this a known behavior of 'do'? I suppose that the Perl interpreter hasn't executed the first part of the hash when the self-reference is encountered. What's the best way to deal with this issue? Thanks, John
  • Comment on retrieving persistent variables with Data::Dumper followed by the 'do' command
  • Download Code

Replies are listed 'Best First'.
Re: retrieving persistent variables with Data::Dumper followed by the 'do' command
by LanX (Saint) on Oct 13, 2014 at 01:50 UTC
    try setting $Data::Dumper::Purity=1; works for me afterwards!

    HTH! :)

    Cheers Rolf

    (addicted to the Perl Programming Language and ☆☆☆☆ :)

    PS: from Data::Dumper

    · $Data::Dumper::Purity or $OBJ->Purity([NEWVAL]) Controls the degree to which the output can be "eval"ed to +recreate the supplied reference structures. Setting it to 1 will ou +tput additional perl statements that will correctly recreate nes +ted references. The default is 0.

    update

    you may wanna have a look at the alternative Data::Dump module! :)

      Thanks, Rolf! I'm embarrassed that I didn't read the documentation, where it is explained very clearly. Cheers, John
Re: retrieving persistent variables with Data::Dumper followed by the 'do' command
by TomDLux (Vicar) on Oct 14, 2014 at 09:42 UTC

    I like Data::Dumper, or more recently Data::Dump, for printing data structures prettily.

    For storing and retrieving data, I would use Jason or Yaml or modules with 'storable' or 'freeze' or 'thaw' in their name.

    As Occam said: Entia non sunt multiplicanda praeter necessitatem.