views:

69

answers:

2

I was trying to serialize some (Moose) objects with YAML -- simply by using YAML's Dump() and Load(). After loading a serialized object, it didn't 'work' until I added a use statement with the original module name. If I don't use use I won't get any error until I try to invoke some object method, then it will croak saying it can't find this method.

I thought loading the needed classes is part of the de-serializer job, and if I'm not mistaken Storable indeed does it by itself.So is there anything broken with YAML?

Also, I noticed the version of the module is not stored with the serialized object. Any way to add it?

+5  A: 

Serialization is for data, not behavior. An object in Perl is just a blessed reference. YAML and Storable serialize and store the data (including the blessing), but that's just the name of the class, not the class itself. You're responsible for loading the class (and any parent classes) when deserializing an object.

In the general case, serializers can't load the class. While the convention is that package (class) == file name, it isn't required. A module can define any package name it wants, or multiple packages. For example, I might write a module named AbstractSyntaxTree.pm that defined the classes Node, Branch, and Leaf.

Michael Carman
Well, I can't find it now, but I was just recently told (here) that I only need to `use` an object class if I'm about to use class methods on it (aka `new`) or if it exports anything I'd like to import (which, as an object class, it shouldn't). I guess it wans't accurate...
David B
@David B: You're confusing a couple of different things. Having a `use` statement is required for importing symbols or subs. For OO, the only requirement is that the module (class) be loaded somewhere. If it isn't method resolution would fail. It doesn't matter if it's a class method (like `new`) or an object method.
Michael Carman
Yup, but what I was told is that the de-serializer is responsible to load all of its serialized objects modules. Also, it seems `Storable` indeed does it but `YAML` does not.
David B
My reading of the Storable documentation leads me to believe that loading the class is not a feature but more a side-effect of looking for a `STORABLE_thaw` method. The documentation includes a caveat about cases where it can fail. It does not attempt to handle inheritance chains, either. It's best to load the classes yourself.
Michael Carman
Michael, Thank you for the kind attention.
David B
+2  A: 

Also, I noticed the version of the module is not stored with the serialized object. Any way to add it?

No, objects only know the package they were blessed into. You can use the use Module VERSION syntax to require some version of the module in the both environments.

eugene y