Beefy Boxes and Bandwidth Generously Provided by pair Networks
laziness, impatience, and hubris
 
PerlMonks  

How to save and reload my hash

by lepetitalbert (Monsignor)
on Nov 20, 2005 at 06:12 UTC ( #510202=perlquestion: print w/ replies, xml ) Need Help??
lepetitalbert has asked for the wisdom of the Perl Monks concerning the following question:

Hello dear Monks,

I have the following data structure.

I'd like to :
- store this hash in a file.
- reload the file in a hash.

I read about Storable , YAML , Data::Dumper , MLDBM , ...

but am lost (again!) with these 'freeze' , 'thaw' , 'bless' , ...

The only thing I was able to do is save the hash to a file with :

print FILE Dumper (\%host_info);

But is it a way to reload this in my %host_info ?

How can I save and reload my hash ?

Thanks.

Have a nice day.

"There is only one good, namely knowledge, and only one evil, namely ignorance." Socrates

Comment on How to save and reload my hash
Download Code
Re: How to save and reload my hash
by ivancho (Hermit) on Nov 20, 2005 at 06:20 UTC
    first 3 lines of Storable's synopsis:
    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')};

      Storable works great for me! Thanks to a five year old post.

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

        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).

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;
Re: How to save and reload my hash
by GrandFather (Cardinal) on Nov 20, 2005 at 08:05 UTC

    Take a look at XML::Simple. It does exactly what you want:

    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
      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.
Re: How to save and reload my hash
by planetscape (Canon) 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,

    planetscape
Re: How to save and reload my hash
by davidrw (Prior) on Nov 20, 2005 at 12:30 UTC
    Also have a look at Cache::FileCache:
    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;

      Hello dear Monks,

      first thanks for you answers.

      I first tried : (cos it's the shortest)

      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
        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.
Re: How to save and reload my hash
by dcronin135 (Novice) 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;

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://510202]
Approved by Tanktalus
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others having an uproarious good time at the Monastery: (7)
As of 2014-12-27 00:55 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    Is guessing a good strategy for surviving in the IT business?





    Results (176 votes), past polls