Data Serialization in Perl examples

One can store data and objects into a file using Serialization. The bytes that is generated can then be re-used to generate an object that will be identical (a clone) to the stored object. We can achieve this by using Storable module from CPAN. The example below will show a way to store and retrieve such objects.

#!/usr/bin/perl

use 5.006;
use strict;
use warnings;
use Data::Dumper;
use Storable;

my %hash1 = ('Test1' => '10',
	     'Test2' => '20');

store %hash1, "serialized_file";
print "##### HASH1 #####n";
print Dumper(%hash1);

my %hash2 = %{retrieve "serialized_file"};
print "n##### HASH2 #####n";
print Dumper(%hash2);

exit 0;

Output:

##### HASH1 #####
$VAR1 = {
          'Test2' => '20',
          'Test1' => '10'
        };

##### HASH2 #####
$VAR1 = {
          'Test2' => '20',
          'Test1' => '10'
        };


For more info see perldoc Storable
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.

Author: Pradeep Pant

Software Engineer

Leave a Reply

Your email address will not be published. Required fields are marked *