2 # Copyright (c) 1995-2000, Raphael Manfredi
4 # You may redistribute only under the same terms as Perl 5, as specified
5 # in the README file that comes with the distribution.
10 package Storable; @ISA = qw(Exporter);
12 @EXPORT = qw(store retrieve);
14 nstore store_fd nstore_fd fd_retrieve
18 lock_store lock_nstore lock_retrieve
22 use vars qw($canonical $forgive_me $VERSION);
27 if (eval { local $SIG{__DIE__}; require Log::Agent; 1 }) {
31 # Use of Log::Agent is optional. If it hasn't imported these subs then
32 # provide a fallback implementation.
34 if (!exists &logcroak) {
40 if (!exists &logcarp) {
49 # They might miss :flock in Fcntl
53 if (eval { require Fcntl; 1 } && exists $Fcntl::EXPORT_TAGS{'flock'}) {
54 Fcntl->import(':flock');
64 # clone context under threads
65 Storable::init_perinterp();
68 # By default restricted hashes are downgraded on earlier perls.
70 $Storable::downgrade_restricted = 1;
71 $Storable::accept_future_minor = 1;
73 XSLoader::load('Storable', $Storable::VERSION);
76 # Determine whether locking is possible, but only when needed.
79 sub CAN_FLOCK; my $CAN_FLOCK; sub CAN_FLOCK {
80 return $CAN_FLOCK if defined $CAN_FLOCK;
81 require Config; import Config;
84 $Config{'d_fcntl_can_lock'} ||
91 # To recognize the data files of the Perl module Storable,
92 # the following lines need to be added to the local magic(5) file,
93 # usually either /usr/share/misc/magic or /etc/magic.
95 0 string perl-store perl Storable(v0.6) data
96 >4 byte >0 (net-order %d)
97 >>4 byte &01 (network-ordered)
101 0 string pst0 perl Storable(v0.7) data
103 >>4 byte &01 (network-ordered)
104 >>4 byte =5 (major 2)
105 >>4 byte =4 (major 2)
106 >>5 byte >0 (minor %d)
114 my $fh = IO::File->new;
115 open($fh, "<". $file) || die "Can't open '$file': $!";
117 defined(sysread($fh, my $buf, 32)) || die "Can't read from '$file': $!";
120 $file = "./$file" unless $file; # ensure TRUE value
122 return read_magic($buf, $file);
126 my($buf, $file) = @_;
129 my $buflen = length($buf);
131 if ($buf =~ s/^(pst0|perl-store)//) {
133 $info{file} = $file || 1;
136 return undef if $file;
140 return undef unless length($buf);
143 if ($magic eq "perl-store" && ord(substr($buf, 0, 1)) > 1) {
149 my $major = (ord $1) >> 1;
150 return undef if $major > 4; # sanity (assuming we never go that high)
151 $info{major} = $major;
152 $net_order = (ord $1) & 0x01;
154 return undef unless $buf =~ s/(.)//s;
156 $info{minor} = $minor;
157 $info{version} = "$major.$minor";
158 $info{version_nv} = sprintf "%d.%03d", $major, $minor;
161 $info{version} = $major;
164 $info{version_nv} ||= $info{version};
165 $info{netorder} = $net_order;
167 unless ($net_order) {
168 return undef unless $buf =~ s/(.)//s;
170 return undef unless length($buf) >= $len;
171 return undef unless $len == 4 || $len == 8; # sanity
172 @info{qw(byteorder intsize longsize ptrsize)}
173 = unpack "a${len}CCC", $buf;
174 (substr $buf, 0, $len + 3) = '';
175 if ($info{version_nv} >= 2.002) {
176 return undef unless $buf =~ s/(.)//s;
177 $info{nvsize} = ord $1;
180 $info{hdrsize} = $buflen - length($buf);
186 sprintf "%d.%03d", BIN_MAJOR(), BIN_MINOR();
189 sub BIN_WRITE_VERSION_NV {
190 sprintf "%d.%03d", BIN_MAJOR(), BIN_WRITE_MINOR();
196 # Store target object hierarchy, identified by a reference to its root.
197 # The stored object tree may later be retrieved to memory via retrieve.
198 # Returns undef if an I/O error occurred, in which case the file is
202 return _store(\&pstore, @_, 0);
208 # Same as store, but in network order.
211 return _store(\&net_pstore, @_, 0);
217 # Same as store, but flock the file first (advisory locking).
220 return _store(\&pstore, @_, 1);
226 # Same as nstore, but flock the file first (advisory locking).
229 return _store(\&net_pstore, @_, 1);
232 # Internal store to file routine
236 my ($file, $use_locking) = @_;
237 logcroak "not a reference" unless ref($self);
238 logcroak "wrong argument number" unless @_ == 2; # No @foo in arglist
241 open(FILE, ">>$file") || logcroak "can't write into $file: $!";
242 unless (&CAN_FLOCK) {
243 logcarp "Storable::lock_store: fcntl/flock emulation broken on $^O";
246 flock(FILE, LOCK_EX) ||
247 logcroak "can't get exclusive lock on $file: $!";
249 # Unlocking will happen when FILE is closed
251 open(FILE, ">$file") || logcroak "can't create $file: $!";
253 binmode FILE; # Archaic systems...
254 my $da = $@; # Don't mess if called from exception handler
256 # Call C routine nstore or pstore, depending on network order
257 eval { $ret = &$xsptr(*FILE, $self) };
258 # close will return true on success, so the or short-circuits, the ()
259 # expression is true, and for that case the block will only be entered
260 # if $@ is true (ie eval failed)
261 # if close fails, it returns false, $ret is altered, *that* is (also)
262 # false, so the () expression is false, !() is true, and the block is
264 if (!(close(FILE) or undef $ret) || $@) {
265 unlink($file) or warn "Can't unlink $file: $!\n";
267 logcroak $@ if $@ =~ s/\.?\n$/,/;
275 # Same as store, but perform on an already opened file descriptor instead.
276 # Returns undef if an I/O error occurred.
279 return _store_fd(\&pstore, @_);
285 # Same as store_fd, but in network order.
288 my ($self, $file) = @_;
289 return _store_fd(\&net_pstore, @_);
292 # Internal store routine on opened file descriptor
297 logcroak "not a reference" unless ref($self);
298 logcroak "too many arguments" unless @_ == 1; # No @foo in arglist
299 my $fd = fileno($file);
300 logcroak "not a valid file descriptor" unless defined $fd;
301 my $da = $@; # Don't mess if called from exception handler
303 # Call C routine nstore or pstore, depending on network order
304 eval { $ret = &$xsptr($file, $self) };
305 logcroak $@ if $@ =~ s/\.?\n$/,/;
306 local $\; print $file ''; # Autoflush the file if wanted
314 # Store oject and its hierarchy in memory and return a scalar
315 # containing the result.
318 _freeze(\&mstore, @_);
324 # Same as freeze but in network order.
327 _freeze(\&net_mstore, @_);
330 # Internal freeze routine
334 logcroak "not a reference" unless ref($self);
335 logcroak "too many arguments" unless @_ == 0; # No @foo in arglist
336 my $da = $@; # Don't mess if called from exception handler
338 # Call C routine mstore or net_mstore, depending on network order
339 eval { $ret = &$xsptr($self) };
340 logcroak $@ if $@ =~ s/\.?\n$/,/;
342 return $ret ? $ret : undef;
348 # Retrieve object hierarchy from disk, returning a reference to the root
349 # object of that tree.
358 # Same as retrieve, but with advisory locking.
364 # Internal retrieve routine
366 my ($file, $use_locking) = @_;
368 open(FILE, $file) || logcroak "can't open $file: $!";
369 binmode FILE; # Archaic systems...
371 my $da = $@; # Could be from exception handler
373 unless (&CAN_FLOCK) {
374 logcarp "Storable::lock_store: fcntl/flock emulation broken on $^O";
377 flock(FILE, LOCK_SH) || logcroak "can't get shared lock on $file: $!";
378 # Unlocking will happen when FILE is closed
380 eval { $self = pretrieve(*FILE) }; # Call C routine
382 logcroak $@ if $@ =~ s/\.?\n$/,/;
390 # Same as retrieve, but perform from an already opened file descriptor instead.
394 my $fd = fileno($file);
395 logcroak "not a valid file descriptor" unless defined $fd;
397 my $da = $@; # Could be from exception handler
398 eval { $self = pretrieve($file) }; # Call C routine
399 logcroak $@ if $@ =~ s/\.?\n$/,/;
404 sub retrieve_fd { &fd_retrieve } # Backward compatibility
409 # Recreate objects in memory from an existing frozen image created
410 # by freeze. If the frozen image passed is undef, return undef.
414 return undef unless defined $frozen;
416 my $da = $@; # Could be from exception handler
417 eval { $self = mretrieve($frozen) }; # Call C routine
418 logcroak $@ if $@ =~ s/\.?\n$/,/;
428 Storable - persistence for Perl data structures
433 store \%table, 'file';
434 $hashref = retrieve('file');
436 use Storable qw(nstore store_fd nstore_fd freeze thaw dclone);
439 nstore \%table, 'file';
440 $hashref = retrieve('file'); # There is NO nretrieve()
442 # Storing to and retrieving from an already opened file
443 store_fd \@array, \*STDOUT;
444 nstore_fd \%table, \*STDOUT;
445 $aryref = fd_retrieve(\*SOCKET);
446 $hashref = fd_retrieve(\*SOCKET);
448 # Serializing to memory
449 $serialized = freeze \%table;
450 %table_clone = %{ thaw($serialized) };
452 # Deep (recursive) cloning
453 $cloneref = dclone($ref);
456 use Storable qw(lock_store lock_nstore lock_retrieve)
457 lock_store \%table, 'file';
458 lock_nstore \%table, 'file';
459 $hashref = lock_retrieve('file');
463 The Storable package brings persistence to your Perl data structures
464 containing SCALAR, ARRAY, HASH or REF objects, i.e. anything that can be
465 conveniently stored to disk and retrieved at a later time.
467 It can be used in the regular procedural way by calling C<store> with
468 a reference to the object to be stored, along with the file name where
469 the image should be written.
471 The routine returns C<undef> for I/O problems or other internal error,
472 a true value otherwise. Serious errors are propagated as a C<die> exception.
474 To retrieve data stored to disk, use C<retrieve> with a file name.
475 The objects stored into that file are recreated into memory for you,
476 and a I<reference> to the root object is returned. In case an I/O error
477 occurs while reading, C<undef> is returned instead. Other serious
478 errors are propagated via C<die>.
480 Since storage is performed recursively, you might want to stuff references
481 to objects that share a lot of common data into a single array or hash
482 table, and then store that object. That way, when you retrieve back the
483 whole thing, the objects will continue to share what they originally shared.
485 At the cost of a slight header overhead, you may store to an already
486 opened file descriptor using the C<store_fd> routine, and retrieve
487 from a file via C<fd_retrieve>. Those names aren't imported by default,
488 so you will have to do that explicitly if you need those routines.
489 The file descriptor you supply must be already opened, for read
490 if you're going to retrieve and for write if you wish to store.
492 store_fd(\%table, *STDOUT) || die "can't store to stdout\n";
493 $hashref = fd_retrieve(*STDIN);
495 You can also store data in network order to allow easy sharing across
496 multiple platforms, or when storing on a socket known to be remotely
497 connected. The routines to call have an initial C<n> prefix for I<network>,
498 as in C<nstore> and C<nstore_fd>. At retrieval time, your data will be
499 correctly restored so you don't have to know whether you're restoring
500 from native or network ordered data. Double values are stored stringified
501 to ensure portability as well, at the slight risk of loosing some precision
502 in the last decimals.
504 When using C<fd_retrieve>, objects are retrieved in sequence, one
505 object (i.e. one recursive tree) per associated C<store_fd>.
507 If you're more from the object-oriented camp, you can inherit from
508 Storable and directly store your objects by invoking C<store> as
509 a method. The fact that the root of the to-be-stored tree is a
510 blessed reference (i.e. an object) is special-cased so that the
511 retrieve does not provide a reference to that object but rather the
512 blessed object reference itself. (Otherwise, you'd get a reference
513 to that blessed object).
517 The Storable engine can also store data into a Perl scalar instead, to
518 later retrieve them. This is mainly used to freeze a complex structure in
519 some safe compact memory place (where it can possibly be sent to another
520 process via some IPC, since freezing the structure also serializes it in
521 effect). Later on, and maybe somewhere else, you can thaw the Perl scalar
522 out and recreate the original complex structure in memory.
524 Surprisingly, the routines to be called are named C<freeze> and C<thaw>.
525 If you wish to send out the frozen scalar to another machine, use
526 C<nfreeze> instead to get a portable image.
528 Note that freezing an object structure and immediately thawing it
529 actually achieves a deep cloning of that structure:
531 dclone(.) = thaw(freeze(.))
533 Storable provides you with a C<dclone> interface which does not create
534 that intermediary scalar but instead freezes the structure in some
535 internal memory space and then immediately thaws it out.
537 =head1 ADVISORY LOCKING
539 The C<lock_store> and C<lock_nstore> routine are equivalent to
540 C<store> and C<nstore>, except that they get an exclusive lock on
541 the file before writing. Likewise, C<lock_retrieve> does the same
542 as C<retrieve>, but also gets a shared lock on the file before reading.
544 As with any advisory locking scheme, the protection only works if you
545 systematically use C<lock_store> and C<lock_retrieve>. If one side of
546 your application uses C<store> whilst the other uses C<lock_retrieve>,
547 you will get no protection at all.
549 The internal advisory locking is implemented using Perl's flock()
550 routine. If your system does not support any form of flock(), or if
551 you share your files across NFS, you might wish to use other forms
552 of locking by using modules such as LockFile::Simple which lock a
553 file using a filesystem entry, instead of locking the file descriptor.
557 The heart of Storable is written in C for decent speed. Extra low-level
558 optimizations have been made when manipulating perl internals, to
559 sacrifice encapsulation for the benefit of greater speed.
561 =head1 CANONICAL REPRESENTATION
563 Normally, Storable stores elements of hashes in the order they are
564 stored internally by Perl, i.e. pseudo-randomly. If you set
565 C<$Storable::canonical> to some C<TRUE> value, Storable will store
566 hashes with the elements sorted by their key. This allows you to
567 compare data structures by comparing their frozen representations (or
568 even the compressed frozen representations), which can be useful for
569 creating lookup tables for complicated queries.
571 Canonical order does not imply network order; those are two orthogonal
574 =head1 CODE REFERENCES
576 Since Storable version 2.05, CODE references may be serialized with
577 the help of L<B::Deparse>. To enable this feature, set
578 C<$Storable::Deparse> to a true value. To enable deserialization,
579 C<$Storable::Eval> should be set to a true value. Be aware that
580 deserialization is done through C<eval>, which is dangerous if the
581 Storable file contains malicious data. You can set C<$Storable::Eval>
582 to a subroutine reference which would be used instead of C<eval>. See
583 below for an example using a L<Safe> compartment for deserialization
586 If C<$Storable::Deparse> and/or C<$Storable::Eval> are set to false
587 values, then the value of C<$Storable::forgive_me> (see below) is
588 respected while serializing and deserializing.
590 =head1 FORWARD COMPATIBILITY
592 This release of Storable can be used on a newer version of Perl to
593 serialize data which is not supported by earlier Perls. By default,
594 Storable will attempt to do the right thing, by C<croak()>ing if it
595 encounters data that it cannot deserialize. However, the defaults
596 can be changed as follows:
602 Perl 5.6 added support for Unicode characters with code points > 255,
603 and Perl 5.8 has full support for Unicode characters in hash keys.
604 Perl internally encodes strings with these characters using utf8, and
605 Storable serializes them as utf8. By default, if an older version of
606 Perl encounters a utf8 value it cannot represent, it will C<croak()>.
607 To change this behaviour so that Storable deserializes utf8 encoded
608 values as the string of bytes (effectively dropping the I<is_utf8> flag)
609 set C<$Storable::drop_utf8> to some C<TRUE> value. This is a form of
610 data loss, because with C<$drop_utf8> true, it becomes impossible to tell
611 whether the original data was the Unicode string, or a series of bytes
612 that happen to be valid utf8.
614 =item restricted hashes
616 Perl 5.8 adds support for restricted hashes, which have keys
617 restricted to a given set, and can have values locked to be read only.
618 By default, when Storable encounters a restricted hash on a perl
619 that doesn't support them, it will deserialize it as a normal hash,
620 silently discarding any placeholder keys and leaving the keys and
621 all values unlocked. To make Storable C<croak()> instead, set
622 C<$Storable::downgrade_restricted> to a C<FALSE> value. To restore
623 the default set it back to some C<TRUE> value.
625 =item files from future versions of Storable
627 Earlier versions of Storable would immediately croak if they encountered
628 a file with a higher internal version number than the reading Storable
629 knew about. Internal version numbers are increased each time new data
630 types (such as restricted hashes) are added to the vocabulary of the file
631 format. This meant that a newer Storable module had no way of writing a
632 file readable by an older Storable, even if the writer didn't store newer
635 This version of Storable will defer croaking until it encounters a data
636 type in the file that it does not recognize. This means that it will
637 continue to read files generated by newer Storable modules which are careful
638 in what they write out, making it easier to upgrade Storable modules in a
641 The old behaviour of immediate croaking can be re-instated by setting
642 C<$Storable::accept_future_minor> to some C<FALSE> value.
646 All these variables have no effect on a newer Perl which supports the
649 =head1 ERROR REPORTING
651 Storable uses the "exception" paradigm, in that it does not try to workaround
652 failures: if something bad happens, an exception is generated from the
653 caller's perspective (see L<Carp> and C<croak()>). Use eval {} to trap
656 When Storable croaks, it tries to report the error via the C<logcroak()>
657 routine from the C<Log::Agent> package, if it is available.
659 Normal errors are reported by having store() or retrieve() return C<undef>.
660 Such errors are usually I/O errors (or truncated stream errors at retrieval).
666 Any class may define hooks that will be called during the serialization
667 and deserialization process on objects that are instances of that class.
668 Those hooks can redefine the way serialization is performed (and therefore,
669 how the symmetrical deserialization should be conducted).
671 Since we said earlier:
673 dclone(.) = thaw(freeze(.))
675 everything we say about hooks should also hold for deep cloning. However,
676 hooks get to know whether the operation is a mere serialization, or a cloning.
678 Therefore, when serializing hooks are involved,
680 dclone(.) <> thaw(freeze(.))
682 Well, you could keep them in sync, but there's no guarantee it will always
683 hold on classes somebody else wrote. Besides, there is little to gain in
684 doing so: a serializing hook could keep only one attribute of an object,
685 which is probably not what should happen during a deep cloning of that
688 Here is the hooking interface:
692 =item C<STORABLE_freeze> I<obj>, I<cloning>
694 The serializing hook, called on the object during serialization. It can be
695 inherited, or defined in the class itself, like any other method.
697 Arguments: I<obj> is the object to serialize, I<cloning> is a flag indicating
698 whether we're in a dclone() or a regular serialization via store() or freeze().
700 Returned value: A LIST C<($serialized, $ref1, $ref2, ...)> where $serialized
701 is the serialized form to be used, and the optional $ref1, $ref2, etc... are
702 extra references that you wish to let the Storable engine serialize.
704 At deserialization time, you will be given back the same LIST, but all the
705 extra references will be pointing into the deserialized structure.
707 The B<first time> the hook is hit in a serialization flow, you may have it
708 return an empty list. That will signal the Storable engine to further
709 discard that hook for this class and to therefore revert to the default
710 serialization of the underlying Perl data. The hook will again be normally
711 processed in the next serialization.
713 Unless you know better, serializing hook should always say:
715 sub STORABLE_freeze {
716 my ($self, $cloning) = @_;
717 return if $cloning; # Regular default serialization
721 in order to keep reasonable dclone() semantics.
723 =item C<STORABLE_thaw> I<obj>, I<cloning>, I<serialized>, ...
725 The deserializing hook called on the object during deserialization.
726 But wait: if we're deserializing, there's no object yet... right?
728 Wrong: the Storable engine creates an empty one for you. If you know Eiffel,
729 you can view C<STORABLE_thaw> as an alternate creation routine.
731 This means the hook can be inherited like any other method, and that
732 I<obj> is your blessed reference for this particular instance.
734 The other arguments should look familiar if you know C<STORABLE_freeze>:
735 I<cloning> is true when we're part of a deep clone operation, I<serialized>
736 is the serialized string you returned to the engine in C<STORABLE_freeze>,
737 and there may be an optional list of references, in the same order you gave
738 them at serialization time, pointing to the deserialized objects (which
739 have been processed courtesy of the Storable engine).
741 When the Storable engine does not find any C<STORABLE_thaw> hook routine,
742 it tries to load the class by requiring the package dynamically (using
743 the blessed package name), and then re-attempts the lookup. If at that
744 time the hook cannot be located, the engine croaks. Note that this mechanism
745 will fail if you define several classes in the same file, but L<perlmod>
748 It is up to you to use this information to populate I<obj> the way you want.
750 Returned value: none.
752 =item C<STORABLE_attach> I<class>, I<cloning>, I<serialized>
754 While C<STORABLE_freeze> and C<STORABLE_thaw> are useful for classes where
755 each instance is independent, this mechanism has difficulty (or is
756 incompatible) with objects that exist as common process-level or
757 system-level resources, such as singleton objects, database pools, caches
760 The alternative C<STORABLE_attach> method provides a solution for these
761 shared objects. Instead of C<STORABLE_freeze> --E<gt> C<STORABLE_thaw>,
762 you implement C<STORABLE_freeze> --E<gt> C<STORABLE_attach> instead.
764 Arguments: I<class> is the class we are attaching to, I<cloning> is a flag
765 indicating whether we're in a dclone() or a regular de-serialization via
766 thaw(), and I<serialized> is the stored string for the resource object.
768 Because these resource objects are considered to be owned by the entire
769 process/system, and not the "property" of whatever is being serialized,
770 no references underneath the object should be included in the serialized
771 string. Thus, in any class that implements C<STORABLE_attach>, the
772 C<STORABLE_freeze> method cannot return any references, and C<Storable>
773 will throw an error if C<STORABLE_freeze> tries to return references.
775 All information required to "attach" back to the shared resource object
776 B<must> be contained B<only> in the C<STORABLE_freeze> return string.
777 Otherwise, C<STORABLE_freeze> behaves as normal for C<STORABLE_attach>
780 Because C<STORABLE_attach> is passed the class (rather than an object),
781 it also returns the object directly, rather than modifying the passed
784 Returned value: object of type C<class>
790 Predicates are not exportable. They must be called by explicitly prefixing
791 them with the Storable package name.
795 =item C<Storable::last_op_in_netorder>
797 The C<Storable::last_op_in_netorder()> predicate will tell you whether
798 network order was used in the last store or retrieve operation. If you
799 don't know how to use this, just forget about it.
801 =item C<Storable::is_storing>
803 Returns true if within a store operation (via STORABLE_freeze hook).
805 =item C<Storable::is_retrieving>
807 Returns true if within a retrieve operation (via STORABLE_thaw hook).
813 With hooks comes the ability to recurse back to the Storable engine.
814 Indeed, hooks are regular Perl code, and Storable is convenient when
815 it comes to serializing and deserializing things, so why not use it
816 to handle the serialization string?
818 There are a few things you need to know, however:
824 You can create endless loops if the things you serialize via freeze()
825 (for instance) point back to the object we're trying to serialize in
830 Shared references among objects will not stay shared: if we're serializing
831 the list of object [A, C] where both object A and C refer to the SAME object
832 B, and if there is a serializing hook in A that says freeze(B), then when
833 deserializing, we'll get [A', C'] where A' refers to B', but C' refers to D,
834 a deep clone of B'. The topology was not preserved.
838 That's why C<STORABLE_freeze> lets you provide a list of references
839 to serialize. The engine guarantees that those will be serialized in the
840 same context as the other objects, and therefore that shared objects will
843 In the above [A, C] example, the C<STORABLE_freeze> hook could return:
845 ("something", $self->{B})
847 and the B part would be serialized by the engine. In C<STORABLE_thaw>, you
848 would get back the reference to the B' object, deserialized for you.
850 Therefore, recursion should normally be avoided, but is nonetheless supported.
854 There is a Clone module available on CPAN which implements deep cloning
855 natively, i.e. without freezing to memory and thawing the result. It is
856 aimed to replace Storable's dclone() some day. However, it does not currently
857 support Storable hooks to redefine the way deep cloning is performed.
859 =head1 Storable magic
861 Yes, there's a lot of that :-) But more precisely, in UNIX systems
862 there's a utility called C<file>, which recognizes data files based on
863 their contents (usually their first few bytes). For this to work,
864 a certain file called F<magic> needs to taught about the I<signature>
865 of the data. Where that configuration file lives depends on the UNIX
866 flavour; often it's something like F</usr/share/misc/magic> or
867 F</etc/magic>. Your system administrator needs to do the updating of
868 the F<magic> file. The necessary signature information is output to
869 STDOUT by invoking Storable::show_file_magic(). Note that the GNU
870 implementation of the C<file> utility, version 3.38 or later,
871 is expected to contain support for recognising Storable files
872 out-of-the-box, in addition to other kinds of Perl files.
874 You can also use the following functions to extract the file header
875 information from Storable images:
879 =item $info = Storable::file_magic( $filename )
881 If the given file is a Storable image return a hash describing it. If
882 the file is readable, but not a Storable image return C<undef>. If
883 the file does not exist or is unreadable then croak.
885 The hash returned has the following elements:
891 This returns the file format version. It is a string like "2.7".
893 Note that this version number is not the same as the version number of
894 the Storable module itself. For instance Storable v0.7 create files
895 in format v2.0 and Storable v2.15 create files in format v2.7. The
896 file format version number only increment when additional features
897 that would confuse older versions of the module are added.
899 Files older than v2.0 will have the one of the version numbers "-1",
900 "0" or "1". No minor number was used at that time.
904 This returns the file format version as number. It is a string like
905 "2.007". This value is suitable for numeric comparisons.
907 The constant function C<Storable::BIN_VERSION_NV> returns a comparable
908 number that represent the highest file version number that this
909 version of Storable fully support (but see discussion of
910 C<$Storable::accept_future_minor> above). The constant
911 C<Storable::BIN_WRITE_VERSION_NV> function returns what file version
912 is written and might be less than C<Storable::BIN_VERSION_NV> in some
915 =item C<major>, C<minor>
917 This also returns the file format version. If the version is "2.7"
918 then major would be 2 and minor would be 7. The minor element is
919 missing for when major is less than 2.
923 The is the number of bytes that the Storable header occupies.
927 This is TRUE if the image store data in network order. This means
928 that it was created with nstore() or similar.
932 This is only present when C<netorder> is FALSE. It is the
933 $Config{byteorder} string of the perl that created this image. It is
934 a string like "1234" (32 bit little endian) or "87654321" (64 bit big
935 endian). This must match the current perl for the image to be
936 readable by Storable.
938 =item C<intsize>, C<longsize>, C<ptrsize>, C<nvsize>
940 These are only present when C<netorder> is FALSE. These are the sizes of
941 various C datatypes of the perl that created this image. These must
942 match the current perl for the image to be readable by Storable.
944 The C<nvsize> element is only present for file format v2.2 and
949 The name of the file.
953 =item $info = Storable::read_magic( $buffer )
955 =item $info = Storable::read_magic( $buffer, $must_be_file )
957 The $buffer should be a Storable image or the first few bytes of it.
958 If $buffer starts with a Storable header, then a hash describing the
959 image is returned, otherwise C<undef> is returned.
961 The hash has the same structure as the one returned by
962 Storable::file_magic(). The C<file> element is true if the image is a
965 If the $must_be_file argument is provided and is TRUE, then return
966 C<undef> unless the image looks like it belongs to a file dump.
968 The maximum size of a Storable header is currently 21 bytes. If the
969 provided $buffer is only the first part of a Storable image it should
970 at least be this long to ensure that read_magic() will recognize it as
977 Here are some code samples showing a possible usage of Storable:
979 use Storable qw(store retrieve freeze thaw dclone);
981 %color = ('Blue' => 0.1, 'Red' => 0.8, 'Black' => 0, 'White' => 1);
983 store(\%color, 'mycolors') or die "Can't store %a in mycolors!\n";
985 $colref = retrieve('mycolors');
986 die "Unable to retrieve from mycolors!\n" unless defined $colref;
987 printf "Blue is still %lf\n", $colref->{'Blue'};
989 $colref2 = dclone(\%color);
991 $str = freeze(\%color);
992 printf "Serialization of %%color is %d bytes long.\n", length($str);
993 $colref3 = thaw($str);
995 which prints (on my machine):
997 Blue is still 0.100000
998 Serialization of %color is 102 bytes long.
1000 Serialization of CODE references and deserialization in a safe
1005 use Storable qw(freeze thaw);
1008 my $safe = new Safe;
1009 # because of opcodes used in "use strict":
1010 $safe->permit(qw(:default require));
1011 local $Storable::Deparse = 1;
1012 local $Storable::Eval = sub { $safe->reval($_[0]) };
1013 my $serialized = freeze(sub { 42 });
1014 my $code = thaw($serialized);
1019 =for example_testing
1020 is( $code->(), 42 );
1024 If you're using references as keys within your hash tables, you're bound
1025 to be disappointed when retrieving your data. Indeed, Perl stringifies
1026 references used as hash table keys. If you later wish to access the
1027 items via another reference stringification (i.e. using the same
1028 reference that was used for the key originally to record the value into
1029 the hash table), it will work because both references stringify to the
1032 It won't work across a sequence of C<store> and C<retrieve> operations,
1033 however, because the addresses in the retrieved objects, which are
1034 part of the stringified references, will probably differ from the
1035 original addresses. The topology of your structure is preserved,
1036 but not hidden semantics like those.
1038 On platforms where it matters, be sure to call C<binmode()> on the
1039 descriptors that you pass to Storable functions.
1041 Storing data canonically that contains large hashes can be
1042 significantly slower than storing the same data normally, as
1043 temporary arrays to hold the keys for each hash have to be allocated,
1044 populated, sorted and freed. Some tests have shown a halving of the
1045 speed of storing -- the exact penalty will depend on the complexity of
1046 your data. There is no slowdown on retrieval.
1050 You can't store GLOB, FORMLINE, REGEXP, etc.... If you can define semantics
1051 for those operations, feel free to enhance Storable so that it can
1054 The store functions will C<croak> if they run into such references
1055 unless you set C<$Storable::forgive_me> to some C<TRUE> value. In that
1056 case, the fatal message is turned in a warning and some
1057 meaningless string is stored instead.
1059 Setting C<$Storable::canonical> may not yield frozen strings that
1060 compare equal due to possible stringification of numbers. When the
1061 string version of a scalar exists, it is the form stored; therefore,
1062 if you happen to use your numbers as strings between two freezing
1063 operations on the same data structures, you will get different
1066 When storing doubles in network order, their value is stored as text.
1067 However, you should also not expect non-numeric floating-point values
1068 such as infinity and "not a number" to pass successfully through a
1069 nstore()/retrieve() pair.
1071 As Storable neither knows nor cares about character sets (although it
1072 does know that characters may be more than eight bits wide), any difference
1073 in the interpretation of character codes between a host and a target
1074 system is your problem. In particular, if host and target use different
1075 code points to represent the characters used in the text representation
1076 of floating-point numbers, you will not be able be able to exchange
1077 floating-point data, even with nstore().
1079 C<Storable::drop_utf8> is a blunt tool. There is no facility either to
1080 return B<all> strings as utf8 sequences, or to attempt to convert utf8
1081 data back to 8 bit and C<croak()> if the conversion fails.
1083 Prior to Storable 2.01, no distinction was made between signed and
1084 unsigned integers on storing. By default Storable prefers to store a
1085 scalars string representation (if it has one) so this would only cause
1086 problems when storing large unsigned integers that had never been converted
1087 to string or floating point. In other words values that had been generated
1088 by integer operations such as logic ops and then not used in any string or
1089 arithmetic context before storing.
1091 =head2 64 bit data in perl 5.6.0 and 5.6.1
1093 This section only applies to you if you have existing data written out
1094 by Storable 2.02 or earlier on perl 5.6.0 or 5.6.1 on Unix or Linux which
1095 has been configured with 64 bit integer support (not the default)
1096 If you got a precompiled perl, rather than running Configure to build
1097 your own perl from source, then it almost certainly does not affect you,
1098 and you can stop reading now (unless you're curious). If you're using perl
1099 on Windows it does not affect you.
1101 Storable writes a file header which contains the sizes of various C
1102 language types for the C compiler that built Storable (when not writing in
1103 network order), and will refuse to load files written by a Storable not
1104 on the same (or compatible) architecture. This check and a check on
1105 machine byteorder is needed because the size of various fields in the file
1106 are given by the sizes of the C language types, and so files written on
1107 different architectures are incompatible. This is done for increased speed.
1108 (When writing in network order, all fields are written out as standard
1109 lengths, which allows full interworking, but takes longer to read and write)
1111 Perl 5.6.x introduced the ability to optional configure the perl interpreter
1112 to use C's C<long long> type to allow scalars to store 64 bit integers on 32
1113 bit systems. However, due to the way the Perl configuration system
1114 generated the C configuration files on non-Windows platforms, and the way
1115 Storable generates its header, nothing in the Storable file header reflected
1116 whether the perl writing was using 32 or 64 bit integers, despite the fact
1117 that Storable was storing some data differently in the file. Hence Storable
1118 running on perl with 64 bit integers will read the header from a file
1119 written by a 32 bit perl, not realise that the data is actually in a subtly
1120 incompatible format, and then go horribly wrong (possibly crashing) if it
1121 encountered a stored integer. This is a design failure.
1123 Storable has now been changed to write out and read in a file header with
1124 information about the size of integers. It's impossible to detect whether
1125 an old file being read in was written with 32 or 64 bit integers (they have
1126 the same header) so it's impossible to automatically switch to a correct
1127 backwards compatibility mode. Hence this Storable defaults to the new,
1130 What this means is that if you have data written by Storable 1.x running
1131 on perl 5.6.0 or 5.6.1 configured with 64 bit integers on Unix or Linux
1132 then by default this Storable will refuse to read it, giving the error
1133 I<Byte order is not compatible>. If you have such data then you you
1134 should set C<$Storable::interwork_56_64bit> to a true value to make this
1135 Storable read and write files with the old header. You should also
1136 migrate your data, or any older perl you are communicating with, to this
1137 current version of Storable.
1139 If you don't have data written with specific configuration of perl described
1140 above, then you do not and should not do anything. Don't set the flag -
1141 not only will Storable on an identically configured perl refuse to load them,
1142 but Storable a differently configured perl will load them believing them
1143 to be correct for it, and then may well fail or crash part way through
1148 Thank you to (in chronological order):
1150 Jarkko Hietaniemi <jhi@iki.fi>
1151 Ulrich Pfeifer <pfeifer@charly.informatik.uni-dortmund.de>
1152 Benjamin A. Holzman <bholzman@earthlink.net>
1153 Andrew Ford <A.Ford@ford-mason.co.uk>
1154 Gisle Aas <gisle@aas.no>
1155 Jeff Gresham <gresham_jeffrey@jpmorgan.com>
1156 Murray Nesbitt <murray@activestate.com>
1157 Marc Lehmann <pcg@opengroup.org>
1158 Justin Banks <justinb@wamnet.com>
1159 Jarkko Hietaniemi <jhi@iki.fi> (AGAIN, as perl 5.7.0 Pumpkin!)
1160 Salvador Ortiz Garcia <sog@msg.com.mx>
1161 Dominic Dunlop <domo@computer.org>
1162 Erik Haugan <erik@solbors.no>
1163 Benjamin A. Holzman <ben.holzman@grantstreet.com>
1165 for their bug reports, suggestions and contributions.
1167 Benjamin Holzman contributed the tied variable support, Andrew Ford
1168 contributed the canonical order for hashes, and Gisle Aas fixed
1169 a few misunderstandings of mine regarding the perl internals,
1170 and optimized the emission of "tags" in the output streams by
1171 simply counting the objects instead of tagging them (leading to
1172 a binary incompatibility for the Storable image starting at version
1173 0.6--older images are, of course, still properly understood).
1174 Murray Nesbitt made Storable thread-safe. Marc Lehmann added overloading
1175 and references to tied items support. Benjamin Holzman added a performance
1176 improvement for overloaded classes; thanks to Grant Street Group for footing
1181 Storable was written by Raphael Manfredi F<E<lt>Raphael_Manfredi@pobox.comE<gt>>
1182 Maintenance is now done by the perl5-porters F<E<lt>perl5-porters@perl.orgE<gt>>
1184 Please e-mail us with problems, bug fixes, comments and complaints,
1185 although if you have compliments you should send them to Raphael.
1186 Please don't e-mail Raphael with problems, as he no longer works on
1187 Storable, and your message will be delayed while he forwards it to us.