Replace #6705 with a minimal doc patch.
[p5sagit/p5-mst-13.2.git] / ext / Storable / Storable.pm
CommitLineData
7a6a85bf 1;# $Id: Storable.pm,v 0.7.1.2 2000/08/14 07:18:40 ram Exp $
2;#
3;# Copyright (c) 1995-2000, Raphael Manfredi
4;#
5;# You may redistribute only under the terms of the Artistic License,
6;# as specified in the README file that comes with the distribution.
7;#
8;# $Log: Storable.pm,v $
9;# Revision 0.7.1.2 2000/08/14 07:18:40 ram
10;# patch2: increased version number
11;#
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
16;#
17;# Revision 0.7 2000/08/03 22:04:44 ram
18;# Baseline for second beta release.
19;#
20
21require DynaLoader;
22require Exporter;
23package Storable; @ISA = qw(Exporter DynaLoader);
24
25@EXPORT = qw(store retrieve);
26@EXPORT_OK = qw(
27 nstore store_fd nstore_fd retrieve_fd
28 freeze nfreeze thaw
29 dclone
30);
31
32use AutoLoader;
33use vars qw($forgive_me $VERSION);
34
35$VERSION = '0.702';
36*AUTOLOAD = \&AutoLoader::AUTOLOAD; # Grrr...
37
38#
39# Use of Log::Agent is optional
40#
41
42eval "use Log::Agent";
43
44unless (defined @Log::Agent::EXPORT) {
45 eval q{
46 sub logcroak {
47 require Carp;
48 Carp::croak(@_);
49 }
50 };
51}
52
53sub logcroak;
54
55bootstrap Storable;
561;
57__END__
58
59#
60# store
61#
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
65# removed.
66#
67sub store {
68 return _store(\&pstore, @_);
69}
70
71#
72# nstore
73#
74# Same as store, but in network order.
75#
76sub nstore {
77 return _store(\&net_pstore, @_);
78}
79
80# Internal store to file routine
81sub _store {
82 my $xsptr = shift;
83 my $self = shift;
84 my ($file) = @_;
85 logcroak "not a reference" unless ref($self);
86 logcroak "too many arguments" unless @_ == 1; # No @foo in arglist
87 local *FILE;
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
91 my $ret;
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$/,/;
97 $@ = $da;
98 return $ret ? $ret : undef;
99}
100
101#
102# store_fd
103#
104# Same as store, but perform on an already opened file descriptor instead.
105# Returns undef if an I/O error occurred.
106#
107sub store_fd {
108 return _store_fd(\&pstore, @_);
109}
110
111#
112# nstore_fd
113#
114# Same as store_fd, but in network order.
115#
116sub nstore_fd {
117 my ($self, $file) = @_;
118 return _store_fd(\&net_pstore, @_);
119}
120
121# Internal store routine on opened file descriptor
122sub _store_fd {
123 my $xsptr = shift;
124 my $self = shift;
125 my ($file) = @_;
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
131 my $ret;
132 # Call C routine nstore or pstore, depending on network order
133 eval { $ret = &$xsptr($file, $self) };
134 logcroak $@ if $@ =~ s/\.?\n$/,/;
135 $@ = $da;
136 return $ret ? $ret : undef;
137}
138
139#
140# freeze
141#
142# Store oject and its hierarchy in memory and return a scalar
143# containing the result.
144#
145sub freeze {
146 _freeze(\&mstore, @_);
147}
148
149#
150# nfreeze
151#
152# Same as freeze but in network order.
153#
154sub nfreeze {
155 _freeze(\&net_mstore, @_);
156}
157
158# Internal freeze routine
159sub _freeze {
160 my $xsptr = shift;
161 my $self = shift;
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
165 my $ret;
166 # Call C routine mstore or net_mstore, depending on network order
167 eval { $ret = &$xsptr($self) };
168 logcroak $@ if $@ =~ s/\.?\n$/,/;
169 $@ = $da;
170 return $ret ? $ret : undef;
171}
172
173#
174# retrieve
175#
176# Retrieve object hierarchy from disk, returning a reference to the root
177# object of that tree.
178#
179sub retrieve {
180 my ($file) = @_;
181 local *FILE;
182 open(FILE, "$file") || logcroak "can't open $file: $!";
183 binmode FILE; # Archaic systems...
184 my $self;
185 my $da = $@; # Could be from exception handler
186 eval { $self = pretrieve(*FILE) }; # Call C routine
187 close(FILE);
188 logcroak $@ if $@ =~ s/\.?\n$/,/;
189 $@ = $da;
190 return $self;
191}
192
193#
194# retrieve_fd
195#
196# Same as retrieve, but perform from an already opened file descriptor instead.
197#
198sub retrieve_fd {
199 my ($file) = @_;
200 my $fd = fileno($file);
201 logcroak "not a valid file descriptor" unless defined $fd;
202 my $self;
203 my $da = $@; # Could be from exception handler
204 eval { $self = pretrieve($file) }; # Call C routine
205 logcroak $@ if $@ =~ s/\.?\n$/,/;
206 $@ = $da;
207 return $self;
208}
209
210#
211# thaw
212#
213# Recreate objects in memory from an existing frozen image created
214# by freeze. If the frozen image passed is undef, return undef.
215#
216sub thaw {
217 my ($frozen) = @_;
218 return undef unless defined $frozen;
219 my $self;
220 my $da = $@; # Could be from exception handler
221 eval { $self = mretrieve($frozen) }; # Call C routine
222 logcroak $@ if $@ =~ s/\.?\n$/,/;
223 $@ = $da;
224 return $self;
225}
226
227=head1 NAME
228
229Storable - persistency for perl data structures
230
231=head1 SYNOPSIS
232
233 use Storable;
234 store \%table, 'file';
235 $hashref = retrieve('file');
236
237 use Storable qw(nstore store_fd nstore_fd freeze thaw dclone);
238
239 # Network order
240 nstore \%table, 'file';
241 $hashref = retrieve('file'); # There is NO nretrieve()
242
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);
248
249 # Serializing to memory
250 $serialized = freeze \%table;
251 %table_clone = %{ thaw($serialized) };
252
253 # Deep (recursive) cloning
254 $cloneref = dclone($ref);
255
256=head1 DESCRIPTION
257
258The Storable package brings persistency to your perl data structures
259containing SCALAR, ARRAY, HASH or REF objects, i.e. anything that can be
260convenientely stored to disk and retrieved at a later time.
261
262It can be used in the regular procedural way by calling C<store> with
263a reference to the object to be stored, along with the file name where
264the image should be written.
265The routine returns C<undef> for I/O problems or other internal error,
266a true value otherwise. Serious errors are propagated as a C<die> exception.
267
268To retrieve data stored to disk, use C<retrieve> with a file name,
269and the objects stored into that file are recreated into memory for you,
270a I<reference> to the root object being returned. In case an I/O error
271occurs while reading, C<undef> is returned instead. Other serious
272errors are propagated via C<die>.
273
274Since storage is performed recursively, you might want to stuff references
275to objects that share a lot of common data into a single array or hash
276table, and then store that object. That way, when you retrieve back the
277whole thing, the objects will continue to share what they originally shared.
278
279At the cost of a slight header overhead, you may store to an already
280opened file descriptor using the C<store_fd> routine, and retrieve
281from a file via C<retrieve_fd>. Those names aren't imported by default,
282so you will have to do that explicitely if you need those routines.
283The file descriptor you supply must be already opened, for read
284if you're going to retrieve and for write if you wish to store.
285
286 store_fd(\%table, *STDOUT) || die "can't store to stdout\n";
287 $hashref = retrieve_fd(*STDIN);
288
289You can also store data in network order to allow easy sharing across
290multiple platforms, or when storing on a socket known to be remotely
291connected. The routines to call have an initial C<n> prefix for I<network>,
292as in C<nstore> and C<nstore_fd>. At retrieval time, your data will be
293correctly restored so you don't have to know whether you're restoring
294from native or network ordered data.
295
296When using C<retrieve_fd>, objects are retrieved in sequence, one
297object (i.e. one recursive tree) per associated C<store_fd>.
298
299If you're more from the object-oriented camp, you can inherit from
300Storable and directly store your objects by invoking C<store> as
301a method. The fact that the root of the to-be-stored tree is a
302blessed reference (i.e. an object) is special-cased so that the
303retrieve does not provide a reference to that object but rather the
304blessed object reference itself. (Otherwise, you'd get a reference
305to that blessed object).
306
307=head1 MEMORY STORE
308
309The Storable engine can also store data into a Perl scalar instead, to
310later retrieve them. This is mainly used to freeze a complex structure in
311some safe compact memory place (where it can possibly be sent to another
312process via some IPC, since freezing the structure also serializes it in
313effect). Later on, and maybe somewhere else, you can thaw the Perl scalar
314out and recreate the original complex structure in memory.
315
316Surprisingly, the routines to be called are named C<freeze> and C<thaw>.
317If you wish to send out the frozen scalar to another machine, use
318C<nfreeze> instead to get a portable image.
319
320Note that freezing an object structure and immediately thawing it
321actually achieves a deep cloning of that structure:
322
323 dclone(.) = thaw(freeze(.))
324
325Storable provides you with a C<dclone> interface which does not create
326that intermediary scalar but instead freezes the structure in some
327internal memory space and then immediatly thaws it out.
328
329=head1 SPEED
330
331The heart of Storable is written in C for decent speed. Extra low-level
332optimization have been made when manipulating perl internals, to
333sacrifice encapsulation for the benefit of a greater speed.
334
335=head1 CANONICAL REPRESENTATION
336
337Normally Storable stores elements of hashes in the order they are
338stored internally by Perl, i.e. pseudo-randomly. If you set
339C<$Storable::canonical> to some C<TRUE> value, Storable will store
340hashes with the elements sorted by their key. This allows you to
341compare data structures by comparing their frozen representations (or
342even the compressed frozen representations), which can be useful for
343creating lookup tables for complicated queries.
344
345Canonical order does not imply network order, those are two orthogonal
346settings.
347
348=head1 ERROR REPORTING
349
350Storable uses the "exception" paradigm, in that it does not try to workaround
351failures: if something bad happens, an exception is generated from the
352caller's perspective (see L<Carp> and C<croak()>). Use eval {} to trap
353those exceptions.
354
355When Storable croaks, it tries to report the error via the C<logcroak()>
356routine from the C<Log::Agent> package, if it is available.
357
358=head1 WIZARDS ONLY
359
360=head2 Hooks
361
362Any class may define hooks that will be called during the serialization
363and deserialization process on objects that are instances of that class.
364Those hooks can redefine the way serialization is performed (and therefore,
365how the symetrical deserialization should be conducted).
366
367Since we said earlier:
368
369 dclone(.) = thaw(freeze(.))
370
371everything we say about hooks should also hold for deep cloning. However,
372hooks get to know whether the operation is a mere serialization, or a cloning.
373
374Therefore, when serializing hooks are involved,
375
376 dclone(.) <> thaw(freeze(.))
377
378Well, you could keep them in sync, but there's no guarantee it will always
379hold on classes somebody else wrote. Besides, there is little to gain in
380doing so: a serializing hook could only keep one attribute of an object,
381which is probably not what should happen during a deep cloning of that
382same object.
383
384Here is the hooking interface:
385
386=over
387
388=item C<STORABLE_freeze> I<obj>, I<cloning>
389
390The serializing hook, called on the object during serialization. It can be
391inherited, or defined in the class itself, like any other method.
392
393Arguments: I<obj> is the object to serialize, I<cloning> is a flag indicating
394whether we're in a dclone() or a regular serialization via store() or freeze().
395
396Returned value: A LIST C<($serialized, $ref1, $ref2, ...)> where $serialized
397is the serialized form to be used, and the optional $ref1, $ref2, etc... are
398extra references that you wish to let the Storable engine serialize.
399
400At deserialization time, you will be given back the same LIST, but all the
401extra references will be pointing into the deserialized structure.
402
403The B<first time> the hook is hit in a serialization flow, you may have it
404return an empty list. That will signal the Storable engine to further
405discard that hook for this class and to therefore revert to the default
406serialization of the underlying Perl data. The hook will again be normally
407processed in the next serialization.
408
409Unless you know better, serializing hook should always say:
410
411 sub STORABLE_freeze {
412 my ($self, $cloning) = @_;
413 return if $cloning; # Regular default serialization
414 ....
415 }
416
417in order to keep reasonable dclone() semantics.
418
419=item C<STORABLE_thaw> I<obj>, I<cloning>, I<serialized>, ...
420
421The deserializing hook called on the object during deserialization.
422But wait. If we're deserializing, there's no object yet... right?
423
424Wrong: the Storable engine creates an empty one for you. If you know Eiffel,
425you can view C<STORABLE_thaw> as an alternate creation routine.
426
427This means the hook can be inherited like any other method, and that
428I<obj> is your blessed reference for this particular instance.
429
430The other arguments should look familiar if you know C<STORABLE_freeze>:
431I<cloning> is true when we're part of a deep clone operation, I<serialized>
432is the serialized string you returned to the engine in C<STORABLE_freeze>,
433and there may be an optional list of references, in the same order you gave
434them at serialization time, pointing to the deserialized objects (which
435have been processed courtesy of the Storable engine).
436
437It is up to you to use these information to populate I<obj> the way you want.
438
439Returned value: none.
440
441=back
442
443=head2 Predicates
444
445Predicates are not exportable. They must be called by explicitely prefixing
446them with the Storable package name.
447
448=over
449
450=item C<Storable::last_op_in_netorder>
451
452The C<Storable::last_op_in_netorder()> predicate will tell you whether
453network order was used in the last store or retrieve operation. If you
454don't know how to use this, just forget about it.
455
456=item C<Storable::is_storing>
457
458Returns true if within a store operation (via STORABLE_freeze hook).
459
460=item C<Storable::is_retrieving>
461
462Returns true if within a retrieve operation, (via STORABLE_thaw hook).
463
464=back
465
466=head2 Recursion
467
468With hooks comes the ability to recurse back to the Storable engine. Indeed,
469hooks are regular Perl code, and Storable is convenient when it comes to
470serialize and deserialize things, so why not use it to handle the
471serialization string?
472
473There are a few things you need to know however:
474
475=over
476
477=item *
478
479You 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.
481
482=item *
483
484Shared references among objects will not stay shared: if we're serializing
485the list of object [A, C] where both object A and C refer to the SAME object
486B, and if there is a serializing hook in A that says freeze(B), then when
487deserializing, we'll get [A', C'] where A' refers to B', but C' refers to D,
488a deep clone of B'. The topology was not preserved.
489
490=back
491
492That's why C<STORABLE_freeze> lets you provide a list of references
493to serialize. The engine guarantees that those will be serialized in the
494same context as the other objects, and therefore that shared objects will
495stay shared.
496
497In the above [A, C] example, the C<STORABLE_freeze> hook could return:
498
499 ("something", $self->{B})
500
501and the B part would be serialized by the engine. In C<STORABLE_thaw>, you
502would get back the reference to the B' object, deserialized for you.
503
504Therefore, recursion should normally be avoided, but is nonetheless supported.
505
506=head2 Deep Cloning
507
508There is a new Clone module available on CPAN which implements deep cloning
509natively, i.e. without freezing to memory and thawing the result. It is
510aimed to replace Storable's dclone() some day. However, it does not currently
511support Storable hooks to redefine the way deep cloning is performed.
512
513=head1 EXAMPLES
514
515Here are some code samples showing a possible usage of Storable:
516
517 use Storable qw(store retrieve freeze thaw dclone);
518
519 %color = ('Blue' => 0.1, 'Red' => 0.8, 'Black' => 0, 'White' => 1);
520
521 store(\%color, '/tmp/colors') or die "Can't store %a in /tmp/colors!\n";
522
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'};
526
527 $colref2 = dclone(\%color);
528
529 $str = freeze(\%color);
530 printf "Serialization of %%color is %d bytes long.\n", length($str);
531 $colref3 = thaw($str);
532
533which prints (on my machine):
534
535 Blue is still 0.100000
536 Serialization of %color is 102 bytes long.
537
538=head1 WARNING
539
540If you're using references as keys within your hash tables, you're bound
541to disapointment when retrieving your data. Indeed, Perl stringifies
542references used as hash table keys. If you later wish to access the
543items via another reference stringification (i.e. using the same
544reference that was used for the key originally to record the value into
545the hash table), it will work because both references stringify to the
546same string.
547
548It won't work across a C<store> and C<retrieve> operations however, because
549the addresses in the retrieved objects, which are part of the stringified
550references, will probably differ from the original addresses. The
551topology of your structure is preserved, but not hidden semantics
552like those.
553
554On platforms where it matters, be sure to call C<binmode()> on the
555descriptors that you pass to Storable functions.
556
557Storing data canonically that contains large hashes can be
558significantly slower than storing the same data normally, as
559temprorary arrays to hold the keys for each hash have to be allocated,
560populated, sorted and freed. Some tests have shown a halving of the
561speed of storing -- the exact penalty will depend on the complexity of
562your data. There is no slowdown on retrieval.
563
564=head1 BUGS
565
566You can't store GLOB, CODE, FORMLINE, etc... If you can define
567semantics for those operations, feel free to enhance Storable so that
568it can deal with them.
569
570The store functions will C<croak> if they run into such references
571unless you set C<$Storable::forgive_me> to some C<TRUE> value. In that
572case, the fatal message is turned in a warning and some
573meaningless string is stored instead.
574
575Setting C<$Storable::canonical> may not yield frozen strings that
576compare equal due to possible stringification of numbers. When the
577string version of a scalar exists, it is the form stored, therefore
578if you happen to use your numbers as strings between two freezing
579operations on the same data structures, you will get different
580results.
581
582Due to the aforementionned optimizations, Storable is at the mercy
583of perl's internal redesign or structure changes. If that bothers
584you, you can try convincing Larry that what is used in Storable
585should be documented and consistently kept in future revisions.
586
587=head1 CREDITS
588
589Thank you to (in chronological order):
590
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>
599
600for their bug reports, suggestions and contributions.
601
602Benjamin Holzman contributed the tied variable support, Andrew Ford
603contributed the canonical order for hashes, and Gisle Aas fixed
604a few misunderstandings of mine regarding the Perl internals,
605and optimized the emission of "tags" in the output streams by
606simply counting the objects instead of tagging them (leading to
607a binary incompatibility for the Storable image starting at version
6080.6--older images are of course still properly understood).
609Murray Nesbitt made Storable thread-safe. Marc Lehmann added overloading
610and reference to tied items support.
611
612=head1 TRANSLATIONS
613
614There is a Japanese translation of this man page available at
615http://member.nifty.ne.jp/hippo2000/perltips/storable.htm ,
616courtesy of Kawai, Takanori <kawai@nippon-rad.co.jp>.
617
618=head1 AUTHOR
619
620Raphael Manfredi F<E<lt>Raphael_Manfredi@pobox.comE<gt>>
621
622=head1 SEE ALSO
623
624Clone(3).
625
626=cut
627