Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw
 
PerlMonks  

Re: How to save and reload my hash

by dcronin135 (Acolyte)
on Sep 23, 2014 at 02:44 UTC ( [id://1101591]=note: print w/replies, xml ) Need Help??


in reply to How to save and reload my hash

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
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1101591]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others browsing the Monastery: (None)
    As of 2024-04-25 00:55 GMT
    Sections?
    Information?
    Find Nodes?
    Leftovers?
      Voting Booth?

      No recent polls found