Re: How to save and reload my hash
by ivancho (Hermit) on Nov 20, 2005 at 06:20 UTC
|
use Storable;
store \%table, 'file';
$hashref = retrieve('file');
second line stores to 'file', third line restores from 'file' ( possibly in another script )
if you wanted a hash instead of a hash ref, wrap the "retrieve" call in %{} - ie,my %host_info = %{retrieve('file')};
| [reply] [d/l] [select] |
|
perl -e '
use Storable;
my $hashfile="file.hash";
store {}, $hashfile unless -r $hashfile;
my $hash=retrieve($hashfile);
print join(",", %$hash), "\n";
$hash->{"index"}++;
store $hash, $hashfile;
'
| [reply] [d/l] |
|
Update: in reply to a four year-old reply to a five (well, nine) year-old post!
Just be aware that nstore is safer than store and nothing is bombproof with Storable except the same particular build and version. Storable is a specialized format, not a standard. If you want a serialization that cannot break on updates, can be used across languages, is usually as fast and sometimes faster than Storable, and happens to be human readable as well, I encourage you to check out JSON(::XS <- for the speed).
| [reply] [d/l] [select] |
|
|
Re: How to save and reload my hash
by planetscape (Chancellor) on Nov 20, 2005 at 09:04 UTC
|
You might also wish to have a look at this, which provides an overview of some of the options for serializing data structures.
HTH,
| [reply] |
Re: How to save and reload my hash
by GrandFather (Saint) on Nov 20, 2005 at 08:05 UTC
|
use XML::Simple;
my $options = XMLin ('teams.badDB') if -e 'teams.badDB';
# do stuff with $options
$options->{'time'} = 15 * 60 if ! exists $options->{'time'};
$options->{'width'} = 200 if ! exists $options->{'width'};
# ...
open outFile, '>', 'teams.badDB';
print outFile XMLout ($options);
close outFile;
DWIM is Perl's answer to Gödel
| [reply] [d/l] |
|
And to greatly speed up XMLin if you have large XML files, you can call it with the parameter Cache=>storable, or other available caching options.
| [reply] |
Re: How to save and reload my hash
by neosamuri (Friar) on Nov 20, 2005 at 07:17 UTC
|
For using data dumper all you havev to do in order to get the data back is use eval to recreate
the data structure. Also of note you should also set $Data::Dumper::Purity to 1 if you have nested references
Here is a example:
#Save
use Data::Dumper;
$Data::Dumper::Purity = 1;
open FILE, ">$outfile" or die "Can't open '$outfile':$!";
print FILE Data::Dumper->Dump([$main], ['*main']);
close FILE;
#restore
open FILE, $infile;
undef $/;
eval <FILE>;
close FILE;
| [reply] [d/l] |
Re: How to save and reload my hash
by karlgoethebier (Abbot) on Mar 25, 2018 at 10:33 UTC
|
"... save and reload..."
A not thoroughly tested little sketch with JSON - the data structure is from the examples planetscape linked to:
Please see also JSON::Tiny and Path::Tiny.
Best regards, Karl
«The Crux of the Biscuit is the Apostrophe»
perl -MCrypt::CBC -E 'say Crypt::CBC->new(-key=>'kgb',-cipher=>"Blowfish")->decrypt_hex($ENV{KARL});'Help
| [reply] [d/l] [select] |
Re: How to save and reload my hash
by davidrw (Prior) on Nov 20, 2005 at 12:30 UTC
|
my $hostname = 'foo.bar.example.com'
use Cache::FileCache;
my $cache = new Cache::FileCache( { 'namespace' => 'HostInfo',
'default_expires_in' => 600 } );
my $cacheKey = $hostname;
my $host_info = $cache->get( $cacheKey );
if ( not defined $host_info )
{
$customer = get_host_info_as_hashref( $hostname );
$cache->set( $cacheKey, $host_info, "10 minutes" );
}
return $host_info;
| [reply] [d/l] |
|
use Storable;
# fill my hash
store \%host_info, 'file';
%host_info = ();
%host_info = %{retrieve('file')};
# print my hash
This worked. Don't know what I did yesterday, when I used store \%host_info, 'file';
(probably not exactly that) It had a file with just
pst01234(and some unprintable chars).
Maybe I should not code until 6am.
Thank you all.
Have a nice day !
"There is only one good, namely knowledge, and only one evil, namely ignorance." Socrates
| [reply] [d/l] [select] |
|
The output that Storable produces is not meant to be human-readable. So it's probably true that whatever you were doing worked just fine. You just have to sort of trust (or test it) that when you read it back in using retrieve it'll come out ok.
| [reply] [d/l] |
Re: How to save and reload my hash
by LanX (Saint) on Mar 24, 2018 at 15:06 UTC
|
FWIW today I was stupid enough to reinvent the wheel with Data::Dump ;-)
use Data::Dump qw/pp/;
#...
if ( -s $file and ! $do_rebuild ) {
warn "reading cache";
$h_func_pod = do $file;
#warn pp '$h_func_pod: ', $h_func_pod;
} else { # rebuild cache
$h_func_pod = parse_by_process();
warn "dumping to cache";
open my $cache, '>', $file;
print $cache ( '+' . pp $h_func_pod); # +{ is never a block
close $cache;
}
| [reply] [d/l] |
Re: How to save and reload my hash
by dcronin135 (Acolyte) on Sep 23, 2014 at 02:44 UTC
|
I ran into this problem, and was very frustrated with the provided examples in getting this to work correctly. Especially on the retrieve, because I could not get the foreach/keys loop to work with the hash after the retrieve. The hash would populate, and could manually plug in the hash of hash values, but, it would not work with the foreach/keys loop. So a peer of mine suggested I try converting the hashref to a hash via %$ construct. I had not seen this before. It worked! After a few trials looking at the hash with Data::Dumper, I was able to get this working using only the Storable module. So now the retrieve side works with the foreach/keys loop. I also provided a JSON example. Yeah !!!
#/usr/bin/perl
# script 1
use Storable;
my %eTAG,$i;
$eTAG{'Truck'}{'Fuel'}="Gas"; $eTAG{'Truck'}{'mpg'}=15;
$eTAG{'SUV'}{'Fuel'}="Gas"; $eTAG{'SUV'}{'mpg'}=21;
#for illustration only
foreach $i (keys %eTAG){ print "$i\n"; }
store \%eTAG, 'fileHash.dat';
exit 0;
Script #2
#!/usr/bin/perl
# Script #2
use Storable;
my $i, $href = retrieve('fileHash.dat',{binmode=>':raw'});
my %eTAG = %$href; #This was the key to getting it working.
foreach $i (keys %eTAG) { print "$i\n"; }
exit 0;
JSON version
#/usr/bin/perl
# script 1 JSON version
use JSON;
my %eTAG,$i;
$eTAG{'Truck'}{'Fuel'}="Gas"; $eTAG{'Truck'}{'mpg'}=15;
$eTAG{'SUV'}{'Fuel'}="Gas"; $eTAG{'SUV'}{'mpg'}=21;
#for illustration only
foreach $i (keys %eTAG){ print "$i\n";}
my $JSONdata = encode_json(\%eTAG);
open(OFIL,">fileHash.dat"); print OFIL $JSONdata; close(OFIL);
exit 0;
#!/usr/bin/perl
# Script #2 JSON version
use JSON;
my $i, $href,$JSONdata;
open(IFIL,"<fileHash.dat"); $JSONdata= <IFIL>; close(IFIL);
$href = decode_json($JSONdata);
my %eTAG = %$href; #This was the key to getting it working.
foreach $i (keys %eTAG) { print "$i $eTAG{$i}{'mpg'}\n"; }
exit 0;
| [reply] [d/l] [select] |