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

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.

Replies are listed 'Best First'.
Re^3: Need Example of Saving and Retrieving Hash from File
by tlm (Prior) on Mar 29, 2005 at 00:45 UTC

    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