#!/usr/bin/perl
use warnings;
use strict;
use Storable;
my $HASHFILE='file';
package main;
sub DoIHaveThisData
{
my ($myhash, $key) = @_;
if (exists $myhash->{$key}) {
return 1;
}
return -1;
}
unless(-e $HASHFILE){
printf "Hash file \'%s\' doesn't exist, creating...\n", $HASHFILE;
my %emptyHash = ();
# Serialize emptyHash, store it in $HASHFILE:
store \%emptyHash, $HASHFILE;
# If we reach here, there should now be an empty hash, serialized in file $HASHFILE
}
# Deserialize the hash, now access it as $hashref:
my $hashref = retrieve($HASHFILE);
# Check to see if key2 is there:
if(DoIHaveThisData($hashref, 'key2')){
printf "Hash has key2! (Value is: \'%s\')\n", $hashref->{'key2'};
}
# Add/Overwrite some data:
$hashref->{'key1'} = 'data1';
$hashref->{'key2'} = 'data2';
$hashref->{'key3'} = 'data3';
# Save the hash for the next time this script runs:
store $hashref, $HASHFILE;
# END OF PROGRAM
####
me@ubuntu01$ rm file
me@ubuntu01$
me@ubuntu01$
me@ubuntu01$ ./SerialHashTest.perl
Hash file 'file' doesn't exist, creating...
Use of uninitialized value in printf at ./SerHash2.perl line 33.
Hash has key2! (Value is: '')
me@ubuntu01$
me@ubuntu01$
me@ubuntu01$ ./SerialHashTest.perl
Hash has key2! (Value is: 'data2')
me@ubuntu01$
me@ubuntu01$
##
##
Use of uninitialized value in printf at ./SerHash2.perl line 33.
Hash has key2! (Value is: '')