1 ;# $Id: Storable.pm,v 0.7.1.2 2000/08/14 07:18:40 ram Exp $
3 ;# Copyright (c) 1995-2000, Raphael Manfredi
5 ;# You may redistribute only under the terms of the Artistic License,
6 ;# as specified in the README file that comes with the distribution.
8 ;# $Log: Storable.pm,v $
9 ;# Revision 0.7.1.2 2000/08/14 07:18:40 ram
10 ;# patch2: increased version number
12 ;# Revision 0.7.1.1 2000/08/13 20:08:58 ram
13 ;# patch1: mention new Clone(3) extension in SEE ALSO
14 ;# patch1: contributor Marc Lehmann added overloading and ref to tied items
15 ;# patch1: updated e-mail from Benjamin Holzman
17 ;# Revision 0.7 2000/08/03 22:04:44 ram
18 ;# Baseline for second beta release.
23 package Storable; @ISA = qw(Exporter DynaLoader);
25 @EXPORT = qw(store retrieve);
27 nstore store_fd nstore_fd retrieve_fd
33 use vars qw($forgive_me $VERSION);
36 *AUTOLOAD = \&AutoLoader::AUTOLOAD; # Grrr...
39 # Use of Log::Agent is optional
42 eval "use Log::Agent";
44 unless (defined @Log::Agent::EXPORT) {
62 # Store target object hierarchy, identified by a reference to its root.
63 # The stored object tree may later be retrieved to memory via retrieve.
64 # Returns undef if an I/O error occurred, in which case the file is
68 return _store(\&pstore, @_);
74 # Same as store, but in network order.
77 return _store(\&net_pstore, @_);
80 # Internal store to file routine
85 logcroak "not a reference" unless ref($self);
86 logcroak "too many arguments" unless @_ == 1; # No @foo in arglist
88 open(FILE, ">$file") || logcroak "can't create $file: $!";
89 binmode FILE; # Archaic systems...
90 my $da = $@; # Don't mess if called from exception handler
92 # Call C routine nstore or pstore, depending on network order
93 eval { $ret = &$xsptr(*FILE, $self) };
94 close(FILE) or $ret = undef;
95 unlink($file) or warn "Can't unlink $file: $!\n" if $@ || !defined $ret;
96 logcroak $@ if $@ =~ s/\.?\n$/,/;
98 return $ret ? $ret : undef;
104 # Same as store, but perform on an already opened file descriptor instead.
105 # Returns undef if an I/O error occurred.
108 return _store_fd(\&pstore, @_);
114 # Same as store_fd, but in network order.
117 my ($self, $file) = @_;
118 return _store_fd(\&net_pstore, @_);
121 # Internal store routine on opened file descriptor
126 logcroak "not a reference" unless ref($self);
127 logcroak "too many arguments" unless @_ == 1; # No @foo in arglist
128 my $fd = fileno($file);
129 logcroak "not a valid file descriptor" unless defined $fd;
130 my $da = $@; # Don't mess if called from exception handler
132 # Call C routine nstore or pstore, depending on network order
133 eval { $ret = &$xsptr($file, $self) };
134 logcroak $@ if $@ =~ s/\.?\n$/,/;
136 return $ret ? $ret : undef;
142 # Store oject and its hierarchy in memory and return a scalar
143 # containing the result.
146 _freeze(\&mstore, @_);
152 # Same as freeze but in network order.
155 _freeze(\&net_mstore, @_);
158 # Internal freeze routine
162 logcroak "not a reference" unless ref($self);
163 logcroak "too many arguments" unless @_ == 0; # No @foo in arglist
164 my $da = $@; # Don't mess if called from exception handler
166 # Call C routine mstore or net_mstore, depending on network order
167 eval { $ret = &$xsptr($self) };
168 logcroak $@ if $@ =~ s/\.?\n$/,/;
170 return $ret ? $ret : undef;
176 # Retrieve object hierarchy from disk, returning a reference to the root
177 # object of that tree.
182 open(FILE, "$file") || logcroak "can't open $file: $!";
183 binmode FILE; # Archaic systems...
185 my $da = $@; # Could be from exception handler
186 eval { $self = pretrieve(*FILE) }; # Call C routine
188 logcroak $@ if $@ =~ s/\.?\n$/,/;
196 # Same as retrieve, but perform from an already opened file descriptor instead.
200 my $fd = fileno($file);
201 logcroak "not a valid file descriptor" unless defined $fd;
203 my $da = $@; # Could be from exception handler
204 eval { $self = pretrieve($file) }; # Call C routine
205 logcroak $@ if $@ =~ s/\.?\n$/,/;
213 # Recreate objects in memory from an existing frozen image created
214 # by freeze. If the frozen image passed is undef, return undef.
218 return undef unless defined $frozen;
220 my $da = $@; # Could be from exception handler
221 eval { $self = mretrieve($frozen) }; # Call C routine
222 logcroak $@ if $@ =~ s/\.?\n$/,/;
229 Storable - persistency for perl data structures
234 store \%table, 'file';
235 $hashref = retrieve('file');
237 use Storable qw(nstore store_fd nstore_fd freeze thaw dclone);
240 nstore \%table, 'file';
241 $hashref = retrieve('file'); # There is NO nretrieve()
243 # Storing to and retrieving from an already opened file
244 store_fd \@array, \*STDOUT;
245 nstore_fd \%table, \*STDOUT;
246 $aryref = retrieve_fd(\*SOCKET);
247 $hashref = retrieve_fd(\*SOCKET);
249 # Serializing to memory
250 $serialized = freeze \%table;
251 %table_clone = %{ thaw($serialized) };
253 # Deep (recursive) cloning
254 $cloneref = dclone($ref);
258 The Storable package brings persistency to your perl data structures
259 containing SCALAR, ARRAY, HASH or REF objects, i.e. anything that can be
260 convenientely stored to disk and retrieved at a later time.
262 It can be used in the regular procedural way by calling C<store> with
263 a reference to the object to be stored, along with the file name where
264 the image should be written.
265 The routine returns C<undef> for I/O problems or other internal error,
266 a true value otherwise. Serious errors are propagated as a C<die> exception.
268 To retrieve data stored to disk, use C<retrieve> with a file name,
269 and the objects stored into that file are recreated into memory for you,
270 a I<reference> to the root object being returned. In case an I/O error
271 occurs while reading, C<undef> is returned instead. Other serious
272 errors are propagated via C<die>.
274 Since storage is performed recursively, you might want to stuff references
275 to objects that share a lot of common data into a single array or hash
276 table, and then store that object. That way, when you retrieve back the
277 whole thing, the objects will continue to share what they originally shared.
279 At the cost of a slight header overhead, you may store to an already
280 opened file descriptor using the C<store_fd> routine, and retrieve
281 from a file via C<retrieve_fd>. Those names aren't imported by default,
282 so you will have to do that explicitely if you need those routines.
283 The file descriptor you supply must be already opened, for read
284 if you're going to retrieve and for write if you wish to store.
286 store_fd(\%table, *STDOUT) || die "can't store to stdout\n";
287 $hashref = retrieve_fd(*STDIN);
289 You can also store data in network order to allow easy sharing across
290 multiple platforms, or when storing on a socket known to be remotely
291 connected. The routines to call have an initial C<n> prefix for I<network>,
292 as in C<nstore> and C<nstore_fd>. At retrieval time, your data will be
293 correctly restored so you don't have to know whether you're restoring
294 from native or network ordered data.
296 When using C<retrieve_fd>, objects are retrieved in sequence, one
297 object (i.e. one recursive tree) per associated C<store_fd>.
299 If you're more from the object-oriented camp, you can inherit from
300 Storable and directly store your objects by invoking C<store> as
301 a method. The fact that the root of the to-be-stored tree is a
302 blessed reference (i.e. an object) is special-cased so that the
303 retrieve does not provide a reference to that object but rather the
304 blessed object reference itself. (Otherwise, you'd get a reference
305 to that blessed object).
309 The Storable engine can also store data into a Perl scalar instead, to
310 later retrieve them. This is mainly used to freeze a complex structure in
311 some safe compact memory place (where it can possibly be sent to another
312 process via some IPC, since freezing the structure also serializes it in
313 effect). Later on, and maybe somewhere else, you can thaw the Perl scalar
314 out and recreate the original complex structure in memory.
316 Surprisingly, the routines to be called are named C<freeze> and C<thaw>.
317 If you wish to send out the frozen scalar to another machine, use
318 C<nfreeze> instead to get a portable image.
320 Note that freezing an object structure and immediately thawing it
321 actually achieves a deep cloning of that structure:
323 dclone(.) = thaw(freeze(.))
325 Storable provides you with a C<dclone> interface which does not create
326 that intermediary scalar but instead freezes the structure in some
327 internal memory space and then immediatly thaws it out.
331 The heart of Storable is written in C for decent speed. Extra low-level
332 optimization have been made when manipulating perl internals, to
333 sacrifice encapsulation for the benefit of a greater speed.
335 =head1 CANONICAL REPRESENTATION
337 Normally Storable stores elements of hashes in the order they are
338 stored internally by Perl, i.e. pseudo-randomly. If you set
339 C<$Storable::canonical> to some C<TRUE> value, Storable will store
340 hashes with the elements sorted by their key. This allows you to
341 compare data structures by comparing their frozen representations (or
342 even the compressed frozen representations), which can be useful for
343 creating lookup tables for complicated queries.
345 Canonical order does not imply network order, those are two orthogonal
348 =head1 ERROR REPORTING
350 Storable uses the "exception" paradigm, in that it does not try to workaround
351 failures: if something bad happens, an exception is generated from the
352 caller's perspective (see L<Carp> and C<croak()>). Use eval {} to trap
355 When Storable croaks, it tries to report the error via the C<logcroak()>
356 routine from the C<Log::Agent> package, if it is available.
362 Any class may define hooks that will be called during the serialization
363 and deserialization process on objects that are instances of that class.
364 Those hooks can redefine the way serialization is performed (and therefore,
365 how the symetrical deserialization should be conducted).
367 Since we said earlier:
369 dclone(.) = thaw(freeze(.))
371 everything we say about hooks should also hold for deep cloning. However,
372 hooks get to know whether the operation is a mere serialization, or a cloning.
374 Therefore, when serializing hooks are involved,
376 dclone(.) <> thaw(freeze(.))
378 Well, you could keep them in sync, but there's no guarantee it will always
379 hold on classes somebody else wrote. Besides, there is little to gain in
380 doing so: a serializing hook could only keep one attribute of an object,
381 which is probably not what should happen during a deep cloning of that
384 Here is the hooking interface:
388 =item C<STORABLE_freeze> I<obj>, I<cloning>
390 The serializing hook, called on the object during serialization. It can be
391 inherited, or defined in the class itself, like any other method.
393 Arguments: I<obj> is the object to serialize, I<cloning> is a flag indicating
394 whether we're in a dclone() or a regular serialization via store() or freeze().
396 Returned value: A LIST C<($serialized, $ref1, $ref2, ...)> where $serialized
397 is the serialized form to be used, and the optional $ref1, $ref2, etc... are
398 extra references that you wish to let the Storable engine serialize.
400 At deserialization time, you will be given back the same LIST, but all the
401 extra references will be pointing into the deserialized structure.
403 The B<first time> the hook is hit in a serialization flow, you may have it
404 return an empty list. That will signal the Storable engine to further
405 discard that hook for this class and to therefore revert to the default
406 serialization of the underlying Perl data. The hook will again be normally
407 processed in the next serialization.
409 Unless you know better, serializing hook should always say:
411 sub STORABLE_freeze {
412 my ($self, $cloning) = @_;
413 return if $cloning; # Regular default serialization
417 in order to keep reasonable dclone() semantics.
419 =item C<STORABLE_thaw> I<obj>, I<cloning>, I<serialized>, ...
421 The deserializing hook called on the object during deserialization.
422 But wait. If we're deserializing, there's no object yet... right?
424 Wrong: the Storable engine creates an empty one for you. If you know Eiffel,
425 you can view C<STORABLE_thaw> as an alternate creation routine.
427 This means the hook can be inherited like any other method, and that
428 I<obj> is your blessed reference for this particular instance.
430 The other arguments should look familiar if you know C<STORABLE_freeze>:
431 I<cloning> is true when we're part of a deep clone operation, I<serialized>
432 is the serialized string you returned to the engine in C<STORABLE_freeze>,
433 and there may be an optional list of references, in the same order you gave
434 them at serialization time, pointing to the deserialized objects (which
435 have been processed courtesy of the Storable engine).
437 It is up to you to use these information to populate I<obj> the way you want.
439 Returned value: none.
445 Predicates are not exportable. They must be called by explicitely prefixing
446 them with the Storable package name.
450 =item C<Storable::last_op_in_netorder>
452 The C<Storable::last_op_in_netorder()> predicate will tell you whether
453 network order was used in the last store or retrieve operation. If you
454 don't know how to use this, just forget about it.
456 =item C<Storable::is_storing>
458 Returns true if within a store operation (via STORABLE_freeze hook).
460 =item C<Storable::is_retrieving>
462 Returns true if within a retrieve operation, (via STORABLE_thaw hook).
468 With hooks comes the ability to recurse back to the Storable engine. Indeed,
469 hooks are regular Perl code, and Storable is convenient when it comes to
470 serialize and deserialize things, so why not use it to handle the
471 serialization string?
473 There are a few things you need to know however:
479 You can create endless loops if the things you serialize via freeze()
480 (for instance) point back to the object we're trying to serialize in the hook.
484 Shared references among objects will not stay shared: if we're serializing
485 the list of object [A, C] where both object A and C refer to the SAME object
486 B, and if there is a serializing hook in A that says freeze(B), then when
487 deserializing, we'll get [A', C'] where A' refers to B', but C' refers to D,
488 a deep clone of B'. The topology was not preserved.
492 That's why C<STORABLE_freeze> lets you provide a list of references
493 to serialize. The engine guarantees that those will be serialized in the
494 same context as the other objects, and therefore that shared objects will
497 In the above [A, C] example, the C<STORABLE_freeze> hook could return:
499 ("something", $self->{B})
501 and the B part would be serialized by the engine. In C<STORABLE_thaw>, you
502 would get back the reference to the B' object, deserialized for you.
504 Therefore, recursion should normally be avoided, but is nonetheless supported.
508 There is a new Clone module available on CPAN which implements deep cloning
509 natively, i.e. without freezing to memory and thawing the result. It is
510 aimed to replace Storable's dclone() some day. However, it does not currently
511 support Storable hooks to redefine the way deep cloning is performed.
515 Here are some code samples showing a possible usage of Storable:
517 use Storable qw(store retrieve freeze thaw dclone);
519 %color = ('Blue' => 0.1, 'Red' => 0.8, 'Black' => 0, 'White' => 1);
521 store(\%color, '/tmp/colors') or die "Can't store %a in /tmp/colors!\n";
523 $colref = retrieve('/tmp/colors');
524 die "Unable to retrieve from /tmp/colors!\n" unless defined $colref;
525 printf "Blue is still %lf\n", $colref->{'Blue'};
527 $colref2 = dclone(\%color);
529 $str = freeze(\%color);
530 printf "Serialization of %%color is %d bytes long.\n", length($str);
531 $colref3 = thaw($str);
533 which prints (on my machine):
535 Blue is still 0.100000
536 Serialization of %color is 102 bytes long.
540 If you're using references as keys within your hash tables, you're bound
541 to disapointment when retrieving your data. Indeed, Perl stringifies
542 references used as hash table keys. If you later wish to access the
543 items via another reference stringification (i.e. using the same
544 reference that was used for the key originally to record the value into
545 the hash table), it will work because both references stringify to the
548 It won't work across a C<store> and C<retrieve> operations however, because
549 the addresses in the retrieved objects, which are part of the stringified
550 references, will probably differ from the original addresses. The
551 topology of your structure is preserved, but not hidden semantics
554 On platforms where it matters, be sure to call C<binmode()> on the
555 descriptors that you pass to Storable functions.
557 Storing data canonically that contains large hashes can be
558 significantly slower than storing the same data normally, as
559 temprorary arrays to hold the keys for each hash have to be allocated,
560 populated, sorted and freed. Some tests have shown a halving of the
561 speed of storing -- the exact penalty will depend on the complexity of
562 your data. There is no slowdown on retrieval.
566 You can't store GLOB, CODE, FORMLINE, etc... If you can define
567 semantics for those operations, feel free to enhance Storable so that
568 it can deal with them.
570 The store functions will C<croak> if they run into such references
571 unless you set C<$Storable::forgive_me> to some C<TRUE> value. In that
572 case, the fatal message is turned in a warning and some
573 meaningless string is stored instead.
575 Setting C<$Storable::canonical> may not yield frozen strings that
576 compare equal due to possible stringification of numbers. When the
577 string version of a scalar exists, it is the form stored, therefore
578 if you happen to use your numbers as strings between two freezing
579 operations on the same data structures, you will get different
582 Due to the aforementionned optimizations, Storable is at the mercy
583 of perl's internal redesign or structure changes. If that bothers
584 you, you can try convincing Larry that what is used in Storable
585 should be documented and consistently kept in future revisions.
589 Thank you to (in chronological order):
591 Jarkko Hietaniemi <jhi@iki.fi>
592 Ulrich Pfeifer <pfeifer@charly.informatik.uni-dortmund.de>
593 Benjamin A. Holzman <bah@ecnvantage.com>
594 Andrew Ford <A.Ford@ford-mason.co.uk>
595 Gisle Aas <gisle@aas.no>
596 Jeff Gresham <gresham_jeffrey@jpmorgan.com>
597 Murray Nesbitt <murray@activestate.com>
598 Marc Lehmann <pcg@opengroup.org>
600 for their bug reports, suggestions and contributions.
602 Benjamin Holzman contributed the tied variable support, Andrew Ford
603 contributed the canonical order for hashes, and Gisle Aas fixed
604 a few misunderstandings of mine regarding the Perl internals,
605 and optimized the emission of "tags" in the output streams by
606 simply counting the objects instead of tagging them (leading to
607 a binary incompatibility for the Storable image starting at version
608 0.6--older images are of course still properly understood).
609 Murray Nesbitt made Storable thread-safe. Marc Lehmann added overloading
610 and reference to tied items support.
614 There is a Japanese translation of this man page available at
615 http://member.nifty.ne.jp/hippo2000/perltips/storable.htm ,
616 courtesy of Kawai, Takanori <kawai@nippon-rad.co.jp>.
620 Raphael Manfredi F<E<lt>Raphael_Manfredi@pobox.comE<gt>>