Making Persistent Data

This pair of routines will serialize and deserialize any Perl data. Useful when you have a piece of data that you want to pass accross 2 CGI applications since CGI don’t have persistent state.


sub _serialize {
   my ($self, $data) = @_;

   my $filename = "/tmp/TTS_$$.dat";

   sysopen(OUTFILE, $filename, O_RDWR|O_CREAT, 0666)
     or die ("Can't open $filename: $!");

   flock(OUTFILE, LOCK_EX)
     or die ("Can't lock $filename: $!");

   store($data, $filename)
     or die ("Can't store data structure: $!");

   flock( OUTFILE, LOCK_UN )
     or die ("Can't unlock $filename: $!");

   return $filename;
}

sub _deserialize {
   my ($self, $filename) = @_;

   sysopen(OUTFILE, $filename, O_RDWR|O_CREAT, 0666)
     or die ("Can't open $filename: $!");

   flock(OUTFILE, LOCK_EX)
     or die ("Can't lock $filename: $!");

   my $data = retrieve($filename)
     or die ("Can't retrieve $filename: $!");

   flock( OUTFILE, LOCK_UN )
     or die ("Can't unlock $filename: $!");

   return $data;
}

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.