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