in reply to Need Example of Saving and Retrieving Hash from File

Here's a crude example:

use Data::Dumper; my %hash = ( foo => 1, bar => 2, baz => 3 ); open my $out, '>', 'save' or die $!; print $out Dumper(\%hash); close $out; open my $in, 'save' or die $!; my $h = eval do { local $/; <$in> }; close $in; print "$_ => $h->{$_}\n" for keys %$h;
But look at the contents of 'save' to see what eval is actually evaluating.

the lowliest monk

Replies are listed 'Best First'.
Re^2: Need Example of Saving and Retrieving Hash from File
by Tanktalus (Canon) on Mar 29, 2005 at 00:28 UTC

    As I said earlier, thawing the data was the hard part. Because yours fails if you use strict. By putting in a "print $@" right after the eval, and enabling strict, you'll see:

    Global symbol "$VAR1" requires explicit package name at (eval 1) line +1, <$in> line 1.
    Not good. The trick? Change your eval line to:
    my $h = eval 'my ' . do { local $/; <$in> };
    We get a lexical "$VAR1" which allows the whole thing to compile. Things don't work so well if you're dumping multiple variables, though. With multiple variables, you either pre-declare all variables using my (or our, or use var), or you split on ;, and put a "my " in front of each variable. The former is dangerous in that you may fail to predeclare some variable, the latter in that a semicolon may show up elsewhere in the data. So it's best to count on a single variable anyway.

      I'm aware of the situation with $VAR1, that's why I cautioned the OP to look at the contents of the file to see what perl is being asked to evaluate. That's one of the reasons why I use Storable instead of Data::Dumper; if I'm stuck with having to use D::D for some reason then I use the two-argument version of Dump so that I can control the names of the LHS variables in the dumped string, and then when I restore I rely on the dumped assignment. E.g., in the storing code:

      print $out Data::Dumper->Dump( [ \%hash ], [ '*dict' ] );
      and in the retrieving code:
      my %dict; eval $dumped_string # initializes %dict or die $@;

      the lowliest monk