Beefy Boxes and Bandwidth Generously Provided by pair Networks
XP is just a number

Object Serialization Basics

by chromatic (Archbishop)
on Apr 19, 2000 at 23:48 UTC ( #8070=perltutorial: print w/replies, xml ) Need Help??

Object Serialization Basics

What is serialization and why does it matter?

Taking an object in memory and making it persistent -- that is, outlasting the life of its fleeting implementation in memory. Perhaps you wish to save the state of your program to disk when it exits, and restore when it starts again. Maybe you want to transfer objects across the network to another instance of your program. You might even store objects in a database.

There are three good modules you may wish to use:

  • Storable
  • FreezeThaw
  • Data::Dumper
my $data = "this is a string of text"; my @dataset = qw( this is an array of text ); my %datagroup = ( hash => "mine", text => "yours" );


Two main methods you'll want to study are Storable::freeze and Storable::thaw. The following is an example of their use:
use Storable; my $stored = freeze [ \$data, \@dataset, \%datagroup ]; print $stored; # just to see what it looks like, in binary encoding my $thawed = thaw $stored; my ($newdata, $newdataset_ref, $newdatagroup_ref) = @$thawed; # cop +ies of original variables (*data, *dataset, *datagroup) = @$thawed; # restore into the origin +al variables
Other useful methods include store() and retrieve(), which provide access to a named disk file.


This also provides freeze() and thaw() methods, but the interface is slightly different:
use FreezeThaw; my $stored = freeze (\$data, \@dataset, \%datagroup); print $stored; # even trickier encoding my @thawed = thaw $stored; my ($newdata, $newdataset_ref, $newdatagroup_ref) = @thawed; (*data, *dataset, *datagroup) = @thawed;
The biggest difference right there is that these methods work on a list, not an anonymous array.

Even better, freeze() and thaw() called on a blessed object (what we really want to persist, right?) calls the Freeze or Thaw method, respectively, of that object. If none is provided, FreezeThaw has already installed UNIVERSAL::Freeze and UNIVERSAL::Thaw.


This module produces Perl output as the encoding language.
my $stored = Data::Dumper->Dump( [ $data, \@dataset, \%datagroup ], [ qw(data *dataset *datagroup )] ); print $stored; eval $stored;
Note that the Dump subroutine takes two anonymous arrays. The first is a list of scalars (or references) to dump, and the second is a list of variables to which to assign the dumped data. (You can leave off the second list, but you'll end up with autogenerated names like $VAR1, $VAR2, and so on.)

Dumping an object results in all of the member data of the object being stored. There's something else magical that happens, though, as evidenced by this dump of an instance of Hello::Hi (from Jellybean):

$hi = bless( { 'Data' => {}, 'Container' => 'Container', 'Info' => { 'modified' => '0', 'name' => 'Hi', 'author' => 'chromatic', 'date' => '1 March 2000', 'desc' => 'silly demonstration for Jellybean' }, 'main' => sub { "DUMMY" }, 'say_hi' => sub { "DUMMY" } }, 'Hello::Hi' );
When this is run through eval() (and assuming you have Hello::Hi available in memory somewhere already), you can call the correct methods. That is, $hi->main() and $hi->say_hi() produce the expected results as if the object had not been dumped and eval()'d.

What Then?

Since these three methods all end up with encoded data stored in a scalar, you can write it to a file or stick it in a database somewhere. You can send it to another process via a pipe, over a socket, or even through an HTTP connection. Decoding it on the other side is also easy.

for more information, see the documentation for Storable, FreezeThaw, and Data::Dumper, or Object Oriented Perl.

Replies are listed 'Best First'.
Re: Object Serialization Basics
by kappa (Chaplain) on Apr 22, 2002 at 12:57 UTC
    Nice tutorial, but I'd like to add a warning:
    If you want to send a Storable-serialized object to another machine via network, then you should use special network-safe method nstore. All other modules mentioned here serialize to text, which is not prone to byte-order and similar platform incompatibilities.
      You'll also want to note that Storable is not platform-independent using nstore across a network with Dec Alpha (64-bit) - see and thread!
      If you are shipping blessed thingies across a network, also make sure that the classes that the thingies are blessed into are loaded (not just installed, but loaded into memory--"use"ed or "require"ed) on the receiving side. If not, the thawing process may fail.
Re: Object Serialization Basics
by belg4mit (Prior) on Apr 24, 2002 at 14:24 UTC
    You highlight the fact that restoration of a Data::Dumperd object will have intact methods, but do not indicate if this is so for the other modules. Is one to assume that by the omission (and latter use of the term "magic") that they are not, cannot be?

    perl -pew "s/\b;([mnst])/'$1/g"

Re: Object Serialization Basics
by polettix (Vicar) on Mar 11, 2006 at 15:45 UTC
    I don't know in 2000, but in 2006 this doesn't work any more:
    my ($newdata, @newdataset, %newdatagroup) = @$thawed;
    @$thawed is an array containing three references; the first is put into $newdata, the other two end up in @newdataset:
    print "$newdata - [@newdataset]\n"; __END__ SCALAR(0x81b5d78) - [ARRAY(0x81b5eb0) HASH(0x812cc00)]

    perl -ple'$_=reverse' <<<ti.xittelop@oivalf

    Don't fool yourself.

      It worked that way in 2000, too. I updated the parent to be clearer about what happens. Thanks!

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perltutorial [id://8070]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others meditating upon the Monastery: (7)
As of 2017-01-19 11:02 GMT
Find Nodes?
    Voting Booth?
    Do you watch meteor showers?

    Results (170 votes). Check out past polls.