Class Serialization in Perl
Submitted by esalazar on Thu, 12/27/2007 - 6:15pm.
::
Serialization in Perl is the process of saving a class with multiple data types to a scalar (string of bytes). This can be used to save objects to a file or to transmit objects across the Internet. For this article I am going to describe the basics of creating a class in Perl and serialize it using the following packages: Data::Dumper, FreezeThaw, PHP::Serialization, and XML::Dumper.
Data types in Perl
Before we serialize anything we first need to learn a bit about the data types in Perl. There are only three data types in Perl, these are scalars, arrays and hash tables. Below is an example of each.
Classes in Perl
Perl was not originally designed to be an object oriented language, although it is possible to use it as one by using the following techniques. A class in Perl is basically just a module that returns a reference to a hash containing the data that is accessible to the class. This referenced is then “blessed” which means that it is bounded to the module. Perl uses some syntactical sugar to make this processes easy. Below is a test class in Perl that uses each of the data types. This class was created to test the serialization of each package.
Perl Serialization Methods
There is no built in serialization in Perl, therefor serialization has to be done with an external package. After searching CPAN I found the following packages.
These packages can be installed by downloading the source code and compiling or by using the following 'cpan' commands.
Serializing TestClass
Below is a program that will serialize TestClass initialized with some sample data. The data will be serialized using all 4 classes.
This is the output from each method:
dataDumper.pl
Unserializing the Data
Below is the program that will unseralize the data from the previous program. Note that any binary data will not be unseralized using XML::Dumper. If you need to serialize binary data with this package, consider first encoding it using UUencode or base64 encode.
Program Output
Conclusion
All of these methods worked well for the given class, although binary to ASCII encoding is necessary for XML serialization. I personally prefer XML serialization because the data can be used with a wide variety of languages. Also XML serialization is human readable.
Data types in Perl
Before we serialize anything we first need to learn a bit about the data types in Perl. There are only three data types in Perl, these are scalars, arrays and hash tables. Below is an example of each.
$myScalar = 'This is a Scalar';Output:
@myArray = ('Element zero','Element one','Element Two');
%myHash = ( keyOne => 'Data1', keyTwo => 'Data2');
print "Scalar Data: " . $myScalar . "\n";
print "Array element at index 1: " . @myArray[1] . "\n";
print "Hash at KeyOne: " . $myHash{'keyOne'} . "\n";
Like in C and C++, you can also have references to the data in each data type. The reference is not the data its self, but a location where the data can be found. By using special syntax the data can be retrieved from the reference itself.Scalar Data: This is a Scalar Array element at index 1: Element one Hash at KeyOne: Data1
$scalarReference = \$myScalar;Output:
$arrayReference = \@myArray;
$hashReference = \%myHash;
print "Scalar Reference: $scalarReference \n";
print "Array Reference: $arrayReference \n";
print "Hash Reference: $hashReference \n";
#Different ways to print the referenced data
print "Scalar Data: " . ${$scalarReference} . "\n"; #Or
print "Scalar Data: " . $$scalarReference . "\n";
print "Array element at index 1: " . @{$arrayReference}[1] . "\n"; #Or
print "Array element at index 1: " . @$arrayReference[1] . "\n"; #Or
print "Array element at index 1: " . $arrayReference->[1] . "\n";
print "Hash at KeyOne: " . ${$hashReference}{'keyOne'} . "\n"; #Or
print "Hash at KeyOne: " . $hashReference->{'keyOne'} . "\n";
Scalar Reference: SCALAR(0x8153600) Array Reference: ARRAY(0x8153630) Hash Reference: HASH(0x8153690) Scalar Data: This is a Scalar Scalar Data: This is a Scalar Array element at index 1: Element one Array element at index 1: Element one Array element at index 1: Element one Hash at KeyOne: Data1 Hash at KeyOne: Data1
Classes in Perl
Perl was not originally designed to be an object oriented language, although it is possible to use it as one by using the following techniques. A class in Perl is basically just a module that returns a reference to a hash containing the data that is accessible to the class. This referenced is then “blessed” which means that it is bounded to the module. Perl uses some syntactical sugar to make this processes easy. Below is a test class in Perl that uses each of the data types. This class was created to test the serialization of each package.
#!/usr/bin/perl
#####################################################
#Author:Evan Salazar
#This is a just a simple perl class that uses
#different data types to be used in serialization
#####################################################
package TestClass;
use strict; #Normally use to keep data clean
#The Constructor
sub new {
print "Creating the Class \n";
my $obj = {
name => {firstName => 'none', lastName => 'none'}, #Test Hash
email => 'none@none.com', #Test Scalar
skills => undef, #Test array
gpgKey => '' }; #Binary Data
bless($obj);
return $obj;
}
#Set the Contact Name
sub setName {
my $self = shift;
$self->{'name'}->{'firstName'} = $_[0];
$self->{'name'}->{'lastName'} = $_[1];
}
#Set the E-Mail
sub setEmail {
my $self = shift;
$self->{'email'} = $_[0];
}
#Set the Skills
sub setSkills {
my $self = shift;
$self->{'skills'} = \@_;
}
#Set the GPG Key
sub setGpgKey {
my $self = shift;
$self->{'gpgKey'} = $_[0];
}
#Print all of the class Data
sub printAll {
my $self = shift;
#Print Full Name
print "Name: " .
$self->{'name'}->{'firstName'} .
" " .
$self->{'name'}->{'firstName'} . "\n";
#Print E-Mail
print "E-Mail: " . $self->{'email'} . "\n";
#Print Skills
print "Skills: ";
for(my $i=0;$i<=$#{$self->{'skills'}};$i++) {
print $self->{'skills'}[$i] . " ";
}
print "\n";
print "GPG Key: " . unpack('H*',$self->{'gpgKey'}) . "\n"
}
1;
Perl Serialization Methods
There is no built in serialization in Perl, therefor serialization has to be done with an external package. After searching CPAN I found the following packages.
- Data::Dumper - Serialize data into Perl code that can then be unserialized using the eval() procedure.
- FreezeThaw - Converts objects to a string for data storage and retrieval.
- PHP::Serialization - Serialize using a method that is compatible with the serialize() method in PHP.
- XML::Dumper - Serialize to XML. Dose not work with binary data.
These packages can be installed by downloading the source code and compiling or by using the following 'cpan' commands.
sudo cpan install Data::Dumper sudo cpan install FreezeThaw sudo cpan install PHP::Serialization sudo cpan install XML::Dumper
Serializing TestClass
Below is a program that will serialize TestClass initialized with some sample data. The data will be serialized using all 4 classes.
#!/usr/bin/perl
#####################################################
#Author: Evan Salazar
#Serialize The data in TestClass
#####################################################
use strict;
use Storable;
use PHP::Serialization;
use FreezeThaw;
use TestClass;
use XML::Dumper;
use Data::Dumper;
#Create the New Test Class
my $myclass = TestClass::new();
#Fill the Test Class with data
$myclass->setName('Evan','Salazar');
$myclass->setEmail('esalazar1981@gmail.com');
$myclass->setSkills('Perl','PHP','Java','C','C++');
#-----Comment out to use XML::Dumper--------------#
$myclass->setGpgKey(pack('H*','11061398fe828dcd83a4b9a79594c399')); #Not really my key but 128bits of random data
#Open File for wrting Serialized Data
open(PHPSER, ">phpser");
open(FREEZETHAW, ">freezeThaw");
open(XMLDUMPER, ">xmldumper.xml");
open(DATADUMPER, ">dataDumper.pl");
#Serialize Using Data::Dumper
print "Data::Dumper\n";
print DATADUMPER Data::Dumper::Dumper($myclass);
#Serialize Using FreezeThaw
print "FreezeThaw\n";
print FREEZETHAW FreezeThaw::freeze($myclass);
#Serialize Using PHP::Serialization
print "PHP::Serializatoin\n";
print PHPSER PHP::Serialization::serialize($myclass);
#Serialize Using XML::Dumper
print "XML::Dumper\n";
my $dump = new XML::Dumper;
print XMLDUMPER $dump->pl2xml($myclass);
This is the output from each method:
dataDumper.pl
FreezeThaw$VAR1 = bless( { 'email' => 'esalazar1981@gmail.com', 'skills' => [ 'Perl', 'PHP', 'Java', 'C', 'C++' ], 'name' => { 'firstName' => 'Evan', 'lastName' => 'Salazar' }, 'gpgKey' => '���������Ù' }, 'TestClass' );
phpserFrT;@1|>>0|$9|TestClass%8|$5|email$6|gpgKey$4|name$6|skills$22|esalazar1981@gmail.com$16|���������Ù%4|$9|firstName$8|lastName$4|Evan$7|Salazar@5|$4|Perl$3|PHP$4|Java$1|C$3|C++
xmldumper.xmlO:9:"TestClass":4:{s:5:"email";s:22:"esalazar1981@gmail.com";s:6:"skills";a:5:{i:0;s:4:"Perl";i:1;s:3:"PHP";i:2;s:4:"Java";i:3;s:1:"C";i:4;s:3:"C++";}s:4:"name";a:2:{s:9:"firstName";s:4:"Evan";s:8:"lastName";s:7:"Salazar";}s:6:"gpgKey";s:16:"���������Ù";}
- esalazar1981@gmail.com
- ���������Ù
- Evan
- Salazar
- Perl
- PHP
- Java
- C
- C++
Unserializing the Data
Below is the program that will unseralize the data from the previous program. Note that any binary data will not be unseralized using XML::Dumper. If you need to serialize binary data with this package, consider first encoding it using UUencode or base64 encode.
#!/usr/bin/perl
#####################################################
#Author: Evan Salazar
#Unserialize the data in TestClass
#####################################################
use strict;
use Storable;
use PHP::Serialization;
use FreezeThaw;
use TestClass;
use XML::Dumper;
use Data::Dumper;
#Set Slurp mode for reading
local($/) = undef;
#Open File for reading Serialized Data
open(PHPSER, "phpser");
open(FREEZETHAW, "freezeThaw");
open(XMLDUMPER, "xmldumper.xml");
open(DATADUMPER, "dataDumper.pl");
#Unserialize Using Data::Dumper
print "Data::Dumper\n";
my $dataDumper = <DATADUMPER>;
#print $dataDumper
my $VAR1;
eval($dataDumper); #Data is stored into variable $VAR1
$VAR1->printAll;
print "\n";
#Unserialize Using FreezeThaw
print "FreezeThaw\n";
my $freezeThaw = <FREEZETHAW>;
#print $freezeThaw;
my ($classFreeze) = FreezeThaw::thaw($freezeThaw);
$classFreeze->printAll;
print "\n";
#Unserialize Using PHP::Serialization
print "PHP::Serializatoin\n";
my $phpser = <PHPSER>;
#print $phpser;
my $classPHP = PHP::Serialization::unserialize($phpser);
bless($classPHP,'TestClass');
$classPHP->printAll;
print "\n";
#Unserialize Using XML::Dumper
print "XML::Dumper\n";
my $xmlDumper = <XMLDUMPER>;
my $dump = new XML::Dumper;
my $xmlClass = $dump->xml2pl($xmlDumper);
$xmlClass->printAll;
Program Output
If you remove the binary data you will getData::Dumper Name: Evan Evan E-Mail: esalazar1981@gmail.com Skills: Perl PHP Java C C++ GPG Key: 11061398fe828dcd83a4b9a79594c399 FreezeThaw Name: Evan Evan E-Mail: esalazar1981@gmail.com Skills: Perl PHP Java C C++ GPG Key: 11061398fe828dcd83a4b9a79594c399 PHP::Serializatoin Name: Evan Evan E-Mail: esalazar1981@gmail.com Skills: Perl PHP Java C C++ GPG Key: 11061398fe828dcd83a4b9a79594c399 XML::Dumper not well-formed (invalid token) at line 4, column 21, byte 148 at /usr/lib/perl5/XML/Parser.pm line 187
Data::Dumper Name: Evan Evan E-Mail: esalazar1981@gmail.com Skills: Perl PHP Java C C++ GPG Key: FreezeThaw Name: Evan Evan E-Mail: esalazar1981@gmail.com Skills: Perl PHP Java C C++ GPG Key: PHP::Serializatoin Name: Evan Evan E-Mail: esalazar1981@gmail.com Skills: Perl PHP Java C C++ GPG Key: XML::Dumper Name: Evan Evan E-Mail: esalazar1981@gmail.com Skills: Perl PHP Java C C++ GPG Key:
Conclusion
All of these methods worked well for the given class, although binary to ASCII encoding is necessary for XML serialization. I personally prefer XML serialization because the data can be used with a wide variety of languages. Also XML serialization is human readable.



1. It is called 'scalar', not 'scaler'.
2. not '@myArray[1]' but $myArray[1]
3. Best module to use for serialization is Storable, and it is in core Perl along with Data::Dumper. You don't need to install them.
I apologize for my misspelling of 'scalar', this has been corrected.
I have found that both '@myArray[1]' and '$myArray[1]' work the same. It would be nice to know the advantages of using one versus the other.
I have not used Storable, but I will try it out.
I seem to recall having to install Data::Dumper, I suppose that it could be in core Perl. I will look into it.
@myArray[1] is a list. You can write @myArray[1,2] to get list of second and third element. $myArray[1] is second element nad is a scalar.
Data::Dumper is core from perl 5.5.
my @array = ('one', 'two', 'three');
my $y = @array[0];
my $x = $array[0];
# $y == 1
# $x eq 'one'
# P.S.
# What's with the CAPTCHA? It's so trivial as to be no deterrent at all.
# It would be far harder to write the spam bot than to solve it.
# P. P. S.
# I'm not implying that writing a spam bot is hard.
Your right about the difference between @array[0] and $array[0]. For the printing above, both work because @array[0] produces a sub array with only one element, but $array[0] would be more "correct".
We have a trivial CAPTCHA just to block 99.9% of spam bots. Our page is not yet popular enough for anyone to waist there time writing a custom spam bot for the sole purpose of spamming us. This is based on the philosophy from www.codinghorror.com who uses a far more trivial CAPTCHA with much more success.
What i would like to ask is if you serialize the object and deserialize it again.
say to a variable xyz. can i use this xyz variable to call any of the subroutines of the class ? i am aksing it because i have seen that once you deserialze it and try to use it fails. but once u load the module in ur code it works? could to explain the logic behind it if you know
The subroutines are stored inside the module. Only the data for the object is serialized, that's why once you deserialize you need to bless the object with the object name so you can use the subroutines of the module with the object.
Thanks alot for this. Highly appreciated.
I can not believe it at all. In pearl? Really? Wow.
FJ5Lj2 ujbilnqjxluo, [url=http://ftazdshoxbhj.com/]ftazdshoxbhj[/url], [link=http://xclonwyiurms.com/]xclonwyiurms[/link], http://sjrctvhcnzvo.com/
a8ByMD xylfronotudp, [url=http://ywizdwrczpwe.com/]ywizdwrczpwe[/url], [link=http://qrvzlfqkezju.com/]qrvzlfqkezju[/link], http://jghbxyztkril.com/
equitable life insurance =-[[[ health insurance sjcfa auto insurance quotes 7504 health care insurance >:)) pennsylvania health insurance =-OO life insurance rates qmigq
Fantastic information and great story. Very happy to read about!
writing services
home insurance ijz health insurance zdb life insurance quotes %OO health insurance :-D auto insurance agency >:((( whole life insurance policies fpu
tramadol hcl-acetaminophen 807736 retin-a 35449 xanax 8-[ acomplia no script pay master card 78151 cheap ultram hfqke online xanax njce
home owner insurance coverage rekbg american home insurance =-) health insurance statistics 248 insurance auto 07601 american home insurance backy auto insurance quotes 239
accutane 8))) phentermine mggokj retin-a rhjmfx pharmacy college buy tramadol gkbf ambien cr and weight loss lhx ultram 50mg 98973
national service life insurance :-)) life insurance quotes %(( health insurance rates %-OO auto insurance rates =OO individual health insurance %-) homeowners insurance california %DD home insurance :-OO
viagra 8935 ultram online drugs 371 description of valium diazepam tablets 0948 propecia 8-] experimental diet drug acomplia 793
retin-a =-D ambien dhk buy accutane fzeze buy phentermine 4938 viagra 24601 ordering ambien online =))
Interesting post. I would also recommend reading or about jackpot also useful information about virus scan and a recommended website for 32red casino review and airplanes and about 90 ball bingo and a site for 888 casino review and a recommended website for Europa League and about casino games and a recommended website for santorini as well as for zakynthos and a recommended website for cefalonia and tips for casino software and regarding slot machine tips or about surebet strategy as well as for online casino and articles for santorini and a website about floor.
car insurance in florida 1373 life of georgia insurance >:PP auto insurance quotes 934134 life insurance quotes 6177 short term health insurance %)) discount auto insurance 8OO
ultram cheap tramadol =-)) valium 8-))) prednisone :-] acomplia =) buy ambien cheap online 6499 valium 08132 ultram %-)))
louisiana homeowners insurance 8-))) auto insurance 4230 home insurance 34005 health insurance coverage xmo health insurance 305 eastwood auto insurance zrwf utah home insurance quote 169
ultram 396559 cheap cialis sale online >:-[ valium 677 ultram 198290 accutane 820
buy phentermine without a prescription uhldr purchase cialis on the internet ymftma phentermine 254 xanax 2260 doxycycline 397 buy propecia in usa oxardv accutane 8-OOO
car insureance xynr life insurance bokul affordable car insurance :-]]] health insurance quotes =-]]] auto insurance quotes 8OO
accutane zkt where to buy prednisone 3598 acomplia emotional eating ksbi ultram and zanaflex fibromyalgia 920 levitra 8-( buy valium europe aiyhcv phentermine =-(((
cialis levitra vs 281323 prednisone ufw ultram 8DD ultram online drugs >:[ buy accutane rsyw xanax =PPP diet pills phentermine =-)))
I agree
custom writing service
garden state life insurance sjndil home insurance quotes >:-PPP cheap health insurance itofqa auto insurance zgxe cheap home insurance 029 cheap life insurance abmmx health insurance quotes qnr
online accutane 8100 acomplia hgjv mp3musics dpr tramadol kfo tramadol qwrn
acomplia 607 valium without prescription 904 ultram 50mg 7638 price of cialis 8OOO ultram =) buy price valium vxqwkk acomplia :-PP
garden state life insurance 5749 florida homeowners insurance prlhfb cheap life insurance :-(( cheap health insurance :) online car insurance >:[[[
accutane purchase :)) no prescription phentermine ygeeqy accutane buy =-DDD viagra 077317 ambien dosage 235 cialis tablet sxdkf
insurance life ymc auto insurance quotes 0657 home insurance rates ehfefu cheap home insurance 78765 cheap auto insurance %))
phentermine rktw cialis :OOO doxycycline 680 buy keyword tramadol cvmy phentermine izr
viagra 165 online accutane 6920 acomplia 8P prednisone hhdwju tramadol nuiitu
mobile home insurance in florida 587 home insurance quotes %-O auto insurance rates 003 life insurance rates lokbug health insurance quotes >:[[[ auto insurance rmy
propecia %OO ultram ccr cialis caiqbo order doxycycline online 51214 experimental diet drug acomplia wvmmq tramadol :-DDD
franklin life insurance %PPP home insurance hypcmz life insurance quotes hqeiqs mobile home insurance arzbmo auto insurance rates =-D cheap life insurance rmqlmt
viagra 148 phentermine 480 order valium stz online store cialis wznsye acomplia :-]] valium 86021
cialis brh prednisone buy 8DDD propecia viagra vbhmd order phentermine 060 acomplia prescription 43383 valium bdvi valium ovrn
life insurance quotes 5192 cheap health insurance aubblj auto insurance rates %-P cheap life insurance 8[[ insurance homeowner >:DDD
viagra on line 199 cialis edqhe viagra >:) cheap cialis sale online ufabzl tramadol online in florida =P doxycycline =)
florida home owners insurance bxrc eastwood auto insurance =]]] best life insurance 103 health insurance plans hcvbfx in home health care insurance elvi child health insurance 079411
Hello! defabbe interesting defabbe site!
phentermine :]]] accutane 31604 generic propecia %O accutane online 3372 purchase prednisone 24546 doxycycline 493588 online physicians cialis ezecgo
viagra no prescription ift xanax %(( price of cialis klizg levitra buy smva valium purchase online from europe 041992 levitra =) order doxycycline online nuihxk
iU7MYx istfhbziskpp, [url=http://mhyutzczhdzc.com/]mhyutzczhdzc[/url], [link=http://zgjscptcscuj.com/]zgjscptcscuj[/link], http://lsltevkzozxb.com/