开发者

Perl persistent data storage using Data::Dumper

开发者 https://www.devze.com 2022-12-24 00:54 出处:网络
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

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 开发者_JAVA百科any help...


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";


We all have those evenings! Try:

$complex_variable = do $MEMORY || die "Bad data";


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号