Hot Pastrami has asked for the wisdom of the Perl Monks concerning the following question:

There are gobs and heaps of cool little Perl tricks that I am ignorant of... this is by virtue of the fact I have done most of my developing until recently in solitary ("solitary" meaning "alone," not "in the hole"). I believe that this is one of those nuggets of info:

Is there an easy way to "serialize" a Perl hash as one can do with objects in Java? If you don't know what serializing is, it's like this... serializing is converting an object to a string which can be stored on disk easily... and when this string is sent to the "deserializer-o-matic," it becomes a whole object again.

For my purposes, the hash may contain refs to hashes, refs to arrays, scalars, or any mixture of the three... and at any depth (the hash can contain a ref to an array of arrays of hashes, etc. No built-in limits, eh!) If no one knows of a relatively easy means to do this, don't feel compelled to write up a sophisticated method for accomplishing it... I can certainly figure it out. I just want to make sure I'm not re-inventing the wheel if I whip one up.

Thanks a bunch,

Alan "Hot Pastrami" Bellows
-Sitting calmly with scissors-

Replies are listed 'Best First'.
Re (tilly) 1: Hash-to-string
by tilly (Archbishop) on Aug 18, 2000 at 00:47 UTC
    I think you will be pleased with Data::Dumper. Also take a look for Storable for a similar concept.
RE: Hash-to-string
by ferrency (Deacon) on Aug 18, 2000 at 00:51 UTC
    It sounds to me like you want the MLDBM module. Using MLDBM, you tie your multi-level data structure to a db file on disk. When you make a change to the structure in memory, it updates it in the db on disk. Voila! Instant persistance for hashes of arrays of hashes of references to arrays of scalars! Or whatever.

    An example of how to use it:

    use MLDBM; tie (%myhash, MLDBM, "filename", O_RDWR|O_CREAT, 0664); %myhash = { one => [0, 1, 2], employee => {serial_num => 1, name => "b +ob"}, mary => 7};
    MLDBM uses Data::Dumper to do the serialization, and stores the resulting serialized structure into a db on disk.

    Hope this is what you were looking for.

    Alan

      But beware of MLDBM when attempting to store things that exceed the DBM's limitation, like 2K for SDBM. Can really ruin a day. Also, MLDBM wants you to always change the top level hash to a completely new value. If you replace something lower, you'll never see it in the data structure.

      Because of these limitations, I prefer using Storable to throw the entire thing into a file on my demand, rather than try to manage the top level piecemeal.

      -- Randal L. Schwartz, Perl hacker