Your skill will accomplish
what the force of many cannot
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:
StorableTwo main methods you'll want to study are Storable::freeze and Storable::thaw. The following is an example of their use:
Other useful methods include store() and retrieve(), which provide access to a named disk file.
FreezeThawThis also provides freeze() and thaw() methods, but the interface is slightly different:
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.
DataDumperThis module produces Perl output as the encoding language.
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):
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.