How-To: Serializing variables in perl

Articles may may have files attached at the end of the post

Serialization is used to store data and objects into a file for instance. The serie of bytes that is generated can then be re-used to generate an object that will be identical (a clone) to the stored object.

In Perl this can be achieved through the Storable module.

This tutorial will quickly show how to store and retrieve such objects.

One of advantage of serialization could be process time. Let say you parse a file and generate an object from that file. If the file is big, it might take quite some time to process.
Serializing the object would allow you to re-read the object from that file at a latter stage for faster processing.

hash, array and scalar can be serialised as follow:

  1. #!/usr/bin/env perl
  2. ##
  3. use warnings;
  4. use strict;
  5.  
  6. use Data::Dumper;
  7. use Storable;
  8.  
  9. my %hash1 = (
  10.             'entry1' => 'value1',
  11.             'entry2' => 'value2'
  12.             );
  13.  
  14. store \%hash1 , "serialized_file.data";
  15. print "##### HASH1 #####\n";
  16. print Dumper(\%hash1);
  17. my %hash2 = %{retrieve "serialized_file.data"};
  18.  
  19. print "\n##### HASH2 #####\n";
  20. print Dumper(\%hash2);
  21.  
  22. exit 0;

will output:

$ ./serialize.pl 
##### HASH1 #####
$VAR1 = {
          'entry2' => 'value2',
          'entry1' => 'value1'
        };

##### HASH2 #####
$VAR1 = {
          'entry2' => 'value2',
          'entry1' => 'value1'
        };

Serializing an object can be done as follow:

  1. #!/usr/bin/env perl
  2. ##
  3. use warnings;
  4. use strict;
  5.  
  6. use Data::Dumper;
  7. use Storable;
  8.  
  9. package Obj;
  10.  
  11. sub new{
  12.   my $class = shift;
  13.   my $self = {};
  14.   bless $self, $class;
  15.   return $self;
  16. }
  17.  
  18. sub set_value{
  19.   my ($self, $val) = @_;
  20.   $self->{data} = $val;
  21. }
  22.  
  23. sub get_value{
  24.   my $self = shift;
  25.   return $self->{data};
  26. }
  27.  
  28. package main;
  29.  
  30. my $obj1 = Obj->new;
  31. $obj1->set_value("serialiased object");
  32.  
  33. store $obj1 , "serialized_file.data";
  34. print "##### OBJ1 #####\n";
  35. print Dumper($obj1);
  36.  
  37. my $obj2 = retrieve "serialized_file.data";
  38. print "\n##### OBJ2 #####\n";
  39. print Dumper($obj2);
  40.  
  41. exit 0;

which will output:

$ ./serialize2.pl 
##### OBJ1 #####
$VAR1 = bless( {
                 'data' => 'serialiased object'
               }, 'Obj' );

##### OBJ2 #####
$VAR1 = bless( {
                 'data' => 'serialiased object'
               }, 'Obj' );

For more information:

$ perldoc Storable

AttachmentSize
serialize.pl.txt386 bytes
serialize2.pl.txt586 bytes