views:

118

answers:

3

I have been trying to figure this out for way to long tonight. I have googled it to death and none of the examples or my hacks of the examples are getting it done. It seems like this should be pretty easy but I just cannot get it. Here is the code:

#!/usr/bin/perl -w
use strict;
use Data::Dumper;

my $complex_variable = {};
my $MEMORY = "$ENV{HOME}/data/memory-file";

$complex_variable->{ 'key' } = 'value';
$complex_variable->{ 'key1' } = 'value1';
$complex_variable->{ 'key2' } = 'value2';
$complex_variable->{ 'key3' } = 'value3';

print Dumper($complex_variable)."TEST001\n";

open M, ">$MEMORY" or die;
print M Data::Dumper->Dump([$complex_variable], ['$complex_variable']);
close M;

$complex_variable = {};
print Dumper($complex_variable)."TEST002\n";

# Then later to restore the value, it's simply:
do $MEMORY;
#eval $MEMORY;

print Dumper($complex_variable)."TEST003\n";   

And here is my output:

$VAR1 = {
         'key2' => 'value2',
         'key1' => 'value1',
         'key3' => 'value3',
         'key' => 'value'
       };
TEST001
$VAR1 = {};
TEST002
$VAR1 = {};
TEST003    

Everything that I read says that the TEST003 output should look identical to the TEST001 output which is exactly what I am trying to achieve.

What am I missing here? Should I be "do"ing differently or should I be "eval"ing instead and if so how?

Thanks for any help...

+5  A: 

We all have those evenings! Try:

$complex_variable = do $MEMORY || die "Bad data";
Gavin Brock
Thanks thats it!
stephenmm
+6  A: 

First, I would recommend using Storable.pm instead of Data::Dumper. Storable has freeze & thaw methods which can preserve a data stucture in it's binary form without translating it to & back from text.

Second, I haven't tried this but it doesn't appear to me you are storing the hashref when you "do $MEMORY" The eval is commented out. Try:

$complex_variable = eval $MEMORY;
print Dumper($complex_variable)."TEST003\n";
joatis
+1 for the Storable mention.
tJener
Storable is the way to go here. And I say this as the guy who has the most recent Data::Dumper upload in his CPAN directory.
tsee
Data::Dump::Streamer is good, if you want to keep the output human-readable.
jrockway
I know. I have been using storable before I tried to use data dumper as it was much easier and I will switch back to storable as my dataset becomes larger. What I needed was the ability for adding new features to the script to be able to see the data that gets stored and to restore it back. This is all for debug as I develope the script more. I will also take a look at Data::Dump::Streamer, thanks!
stephenmm
+1  A: 

I tend to like DBM::Deep for this. However, I have a complete chapter on "Lightweight Persistence" in Mastering Perl that talks about everything short of a database server.

brian d foy
Thanks if my dataset starts getting to large I will investigate...
stephenmm
Um, the stuff I talk about is for small data sets. :)
brian d foy