This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
Switch Storable to XSLoader from DynaLoader
[perl5.git] / dist / Storable / Storable.pm
CommitLineData
25f64a11
AMS
1#
2# Copyright (c) 1995-2000, Raphael Manfredi
3#
4# You may redistribute only under the same terms as Perl 5, as specified
5# in the README file that comes with the distribution.
6#
7a6a85bf 7
71a48636 8require XSLoader;
7a6a85bf 9require Exporter;
71a48636 10package Storable; @ISA = qw(Exporter);
7a6a85bf
RG
11
12@EXPORT = qw(store retrieve);
13@EXPORT_OK = qw(
9e21b3d0 14 nstore store_fd nstore_fd fd_retrieve
7a6a85bf
RG
15 freeze nfreeze thaw
16 dclone
9e21b3d0 17 retrieve_fd
dd19458b 18 lock_store lock_nstore lock_retrieve
d4b9b6e4 19 file_magic read_magic
7a6a85bf
RG
20);
21
22use AutoLoader;
ab6f8ca1 23use FileHandle;
01d7b99e 24use vars qw($canonical $forgive_me $VERSION);
7a6a85bf 25
71a48636 26$VERSION = '2.27';
7a6a85bf
RG
27*AUTOLOAD = \&AutoLoader::AUTOLOAD; # Grrr...
28
29#
30# Use of Log::Agent is optional
31#
32
bb65ef26
AMS
33{
34 local $SIG{__DIE__};
35 eval "use Log::Agent";
36}
7a6a85bf 37
530b72ba 38require Carp;
7a6a85bf 39
dd19458b
JH
40#
41# They might miss :flock in Fcntl
42#
43
44BEGIN {
596596d5 45 if (eval { require Fcntl; 1 } && exists $Fcntl::EXPORT_TAGS{'flock'}) {
dd19458b
JH
46 Fcntl->import(':flock');
47 } else {
48 eval q{
49 sub LOCK_SH () {1}
50 sub LOCK_EX () {2}
51 };
52 }
53}
54
a8b7ef86
AMS
55sub CLONE {
56 # clone context under threads
57 Storable::init_perinterp();
58}
59
b8778c7c 60# Can't Autoload cleanly as this clashes 8.3 with &retrieve
9e21b3d0 61sub retrieve_fd { &fd_retrieve } # Backward compatibility
cb3d9de5 62
530b72ba
NC
63# By default restricted hashes are downgraded on earlier perls.
64
65$Storable::downgrade_restricted = 1;
e8189732 66$Storable::accept_future_minor = 1;
71a48636
DL
67
68XSLoader::load 'Storable', $Storable::VERSION;
b8778c7c
NC
691;
70__END__
530b72ba
NC
71#
72# Use of Log::Agent is optional. If it hasn't imported these subs then
73# Autoloader will kindly supply our fallback implementation.
74#
75
76sub logcroak {
77 Carp::croak(@_);
78}
79
80sub logcarp {
81 Carp::carp(@_);
82}
b8778c7c 83
862382c7
JH
84#
85# Determine whether locking is possible, but only when needed.
86#
87
530b72ba 88sub CAN_FLOCK; my $CAN_FLOCK; sub CAN_FLOCK {
862382c7
JH
89 return $CAN_FLOCK if defined $CAN_FLOCK;
90 require Config; import Config;
91 return $CAN_FLOCK =
92 $Config{'d_flock'} ||
93 $Config{'d_fcntl_can_lock'} ||
94 $Config{'d_lockf'};
95}
96
0a0da639
JH
97sub show_file_magic {
98 print <<EOM;
99#
100# To recognize the data files of the Perl module Storable,
101# the following lines need to be added to the local magic(5) file,
102# usually either /usr/share/misc/magic or /etc/magic.
0a0da639
JH
103#
1040 string perl-store perl Storable(v0.6) data
8b793558
JH
105>4 byte >0 (net-order %d)
106>>4 byte &01 (network-ordered)
107>>4 byte =3 (major 1)
108>>4 byte =2 (major 1)
109
0a0da639 1100 string pst0 perl Storable(v0.7) data
8b793558
JH
111>4 byte >0
112>>4 byte &01 (network-ordered)
113>>4 byte =5 (major 2)
114>>4 byte =4 (major 2)
115>>5 byte >0 (minor %d)
0a0da639
JH
116EOM
117}
118
d4b9b6e4
GA
119sub file_magic {
120 my $file = shift;
ab6f8ca1
AT
121 my $fh = new FileHandle;
122 open($fh, "<". $file) || die "Can't open '$file': $!";
d4b9b6e4
GA
123 binmode($fh);
124 defined(sysread($fh, my $buf, 32)) || die "Can't read from '$file': $!";
125 close($fh);
126
127 $file = "./$file" unless $file; # ensure TRUE value
128
129 return read_magic($buf, $file);
130}
131
b8778c7c 132sub read_magic {
d4b9b6e4
GA
133 my($buf, $file) = @_;
134 my %info;
135
136 my $buflen = length($buf);
137 my $magic;
138 if ($buf =~ s/^(pst0|perl-store)//) {
139 $magic = $1;
140 $info{file} = $file || 1;
141 }
142 else {
143 return undef if $file;
144 $magic = "";
145 }
146
147 return undef unless length($buf);
148
149 my $net_order;
150 if ($magic eq "perl-store" && ord(substr($buf, 0, 1)) > 1) {
151 $info{version} = -1;
152 $net_order = 0;
153 }
154 else {
5e12106f
NC
155 $buf =~ s/(.)//s;
156 my $major = (ord $1) >> 1;
d4b9b6e4
GA
157 return undef if $major > 4; # sanity (assuming we never go that high)
158 $info{major} = $major;
5e12106f 159 $net_order = (ord $1) & 0x01;
d4b9b6e4 160 if ($major > 1) {
5e12106f
NC
161 return undef unless $buf =~ s/(.)//s;
162 my $minor = ord $1;
d4b9b6e4
GA
163 $info{minor} = $minor;
164 $info{version} = "$major.$minor";
165 $info{version_nv} = sprintf "%d.%03d", $major, $minor;
166 }
167 else {
168 $info{version} = $major;
169 }
170 }
171 $info{version_nv} ||= $info{version};
172 $info{netorder} = $net_order;
173
174 unless ($net_order) {
5e12106f
NC
175 return undef unless $buf =~ s/(.)//s;
176 my $len = ord $1;
d4b9b6e4
GA
177 return undef unless length($buf) >= $len;
178 return undef unless $len == 4 || $len == 8; # sanity
5e12106f
NC
179 @info{qw(byteorder intsize longsize ptrsize)}
180 = unpack "a${len}CCC", $buf;
181 (substr $buf, 0, $len + 3) = '';
d4b9b6e4 182 if ($info{version_nv} >= 2.002) {
5e12106f
NC
183 return undef unless $buf =~ s/(.)//s;
184 $info{nvsize} = ord $1;
d4b9b6e4
GA
185 }
186 }
187 $info{hdrsize} = $buflen - length($buf);
188
189 return \%info;
190}
191
192sub BIN_VERSION_NV {
193 sprintf "%d.%03d", BIN_MAJOR(), BIN_MINOR();
194}
195
196sub BIN_WRITE_VERSION_NV {
197 sprintf "%d.%03d", BIN_MAJOR(), BIN_WRITE_MINOR();
b8778c7c 198}
7a6a85bf
RG
199
200#
201# store
202#
203# Store target object hierarchy, identified by a reference to its root.
204# The stored object tree may later be retrieved to memory via retrieve.
205# Returns undef if an I/O error occurred, in which case the file is
206# removed.
207#
208sub store {
dd19458b 209 return _store(\&pstore, @_, 0);
7a6a85bf
RG
210}
211
212#
213# nstore
214#
215# Same as store, but in network order.
216#
217sub nstore {
dd19458b
JH
218 return _store(\&net_pstore, @_, 0);
219}
220
221#
222# lock_store
223#
224# Same as store, but flock the file first (advisory locking).
225#
226sub lock_store {
227 return _store(\&pstore, @_, 1);
228}
229
230#
231# lock_nstore
232#
233# Same as nstore, but flock the file first (advisory locking).
234#
235sub lock_nstore {
236 return _store(\&net_pstore, @_, 1);
7a6a85bf
RG
237}
238
239# Internal store to file routine
240sub _store {
241 my $xsptr = shift;
242 my $self = shift;
dd19458b 243 my ($file, $use_locking) = @_;
7a6a85bf 244 logcroak "not a reference" unless ref($self);
b12202d0 245 logcroak "wrong argument number" unless @_ == 2; # No @foo in arglist
7a6a85bf 246 local *FILE;
dd19458b 247 if ($use_locking) {
6e0ac6f5 248 open(FILE, ">>$file") || logcroak "can't write into $file: $!";
862382c7 249 unless (&CAN_FLOCK) {
b29b780f
RM
250 logcarp "Storable::lock_store: fcntl/flock emulation broken on $^O";
251 return undef;
f567092b 252 }
dd19458b
JH
253 flock(FILE, LOCK_EX) ||
254 logcroak "can't get exclusive lock on $file: $!";
255 truncate FILE, 0;
256 # Unlocking will happen when FILE is closed
6e0ac6f5
JH
257 } else {
258 open(FILE, ">$file") || logcroak "can't create $file: $!";
dd19458b 259 }
6e0ac6f5 260 binmode FILE; # Archaic systems...
7a6a85bf
RG
261 my $da = $@; # Don't mess if called from exception handler
262 my $ret;
263 # Call C routine nstore or pstore, depending on network order
264 eval { $ret = &$xsptr(*FILE, $self) };
9c09e8a7
NC
265 # close will return true on success, so the or short-circuits, the ()
266 # expression is true, and for that case the block will only be entered
267 # if $@ is true (ie eval failed)
268 # if close fails, it returns false, $ret is altered, *that* is (also)
269 # false, so the () expression is false, !() is true, and the block is
270 # entered.
cbc736f3 271 if (!(close(FILE) or undef $ret) || $@) {
9c09e8a7
NC
272 unlink($file) or warn "Can't unlink $file: $!\n";
273 }
7a6a85bf
RG
274 logcroak $@ if $@ =~ s/\.?\n$/,/;
275 $@ = $da;
cbc736f3 276 return $ret;
7a6a85bf
RG
277}
278
279#
280# store_fd
281#
282# Same as store, but perform on an already opened file descriptor instead.
283# Returns undef if an I/O error occurred.
284#
285sub store_fd {
286 return _store_fd(\&pstore, @_);
287}
288
289#
290# nstore_fd
291#
292# Same as store_fd, but in network order.
293#
294sub nstore_fd {
295 my ($self, $file) = @_;
296 return _store_fd(\&net_pstore, @_);
297}
298
299# Internal store routine on opened file descriptor
300sub _store_fd {
301 my $xsptr = shift;
302 my $self = shift;
303 my ($file) = @_;
304 logcroak "not a reference" unless ref($self);
305 logcroak "too many arguments" unless @_ == 1; # No @foo in arglist
306 my $fd = fileno($file);
307 logcroak "not a valid file descriptor" unless defined $fd;
308 my $da = $@; # Don't mess if called from exception handler
309 my $ret;
310 # Call C routine nstore or pstore, depending on network order
311 eval { $ret = &$xsptr($file, $self) };
312 logcroak $@ if $@ =~ s/\.?\n$/,/;
596596d5 313 local $\; print $file ''; # Autoflush the file if wanted
7a6a85bf 314 $@ = $da;
cbc736f3 315 return $ret;
7a6a85bf
RG
316}
317
318#
319# freeze
320#
321# Store oject and its hierarchy in memory and return a scalar
322# containing the result.
323#
324sub freeze {
325 _freeze(\&mstore, @_);
326}
327
328#
329# nfreeze
330#
331# Same as freeze but in network order.
332#
333sub nfreeze {
334 _freeze(\&net_mstore, @_);
335}
336
337# Internal freeze routine
338sub _freeze {
339 my $xsptr = shift;
340 my $self = shift;
341 logcroak "not a reference" unless ref($self);
342 logcroak "too many arguments" unless @_ == 0; # No @foo in arglist
343 my $da = $@; # Don't mess if called from exception handler
344 my $ret;
345 # Call C routine mstore or net_mstore, depending on network order
346 eval { $ret = &$xsptr($self) };
347 logcroak $@ if $@ =~ s/\.?\n$/,/;
348 $@ = $da;
349 return $ret ? $ret : undef;
350}
351
352#
353# retrieve
354#
355# Retrieve object hierarchy from disk, returning a reference to the root
356# object of that tree.
357#
358sub retrieve {
dd19458b
JH
359 _retrieve($_[0], 0);
360}
361
362#
363# lock_retrieve
364#
365# Same as retrieve, but with advisory locking.
366#
367sub lock_retrieve {
368 _retrieve($_[0], 1);
369}
370
371# Internal retrieve routine
372sub _retrieve {
373 my ($file, $use_locking) = @_;
7a6a85bf 374 local *FILE;
dd19458b 375 open(FILE, $file) || logcroak "can't open $file: $!";
7a6a85bf
RG
376 binmode FILE; # Archaic systems...
377 my $self;
378 my $da = $@; # Could be from exception handler
dd19458b 379 if ($use_locking) {
862382c7 380 unless (&CAN_FLOCK) {
8be2b38b 381 logcarp "Storable::lock_store: fcntl/flock emulation broken on $^O";
b29b780f
RM
382 return undef;
383 }
8be2b38b 384 flock(FILE, LOCK_SH) || logcroak "can't get shared lock on $file: $!";
dd19458b
JH
385 # Unlocking will happen when FILE is closed
386 }
7a6a85bf
RG
387 eval { $self = pretrieve(*FILE) }; # Call C routine
388 close(FILE);
389 logcroak $@ if $@ =~ s/\.?\n$/,/;
390 $@ = $da;
391 return $self;
392}
393
394#
9e21b3d0 395# fd_retrieve
7a6a85bf
RG
396#
397# Same as retrieve, but perform from an already opened file descriptor instead.
398#
9e21b3d0 399sub fd_retrieve {
7a6a85bf
RG
400 my ($file) = @_;
401 my $fd = fileno($file);
402 logcroak "not a valid file descriptor" unless defined $fd;
403 my $self;
404 my $da = $@; # Could be from exception handler
405 eval { $self = pretrieve($file) }; # Call C routine
406 logcroak $@ if $@ =~ s/\.?\n$/,/;
407 $@ = $da;
408 return $self;
409}
410
411#
412# thaw
413#
414# Recreate objects in memory from an existing frozen image created
415# by freeze. If the frozen image passed is undef, return undef.
416#
417sub thaw {
418 my ($frozen) = @_;
419 return undef unless defined $frozen;
420 my $self;
421 my $da = $@; # Could be from exception handler
422 eval { $self = mretrieve($frozen) }; # Call C routine
423 logcroak $@ if $@ =~ s/\.?\n$/,/;
424 $@ = $da;
425 return $self;
426}
427
a2307be4
NC
4281;
429__END__
430
7a6a85bf
RG
431=head1 NAME
432
f062ea6c 433Storable - persistence for Perl data structures
7a6a85bf
RG
434
435=head1 SYNOPSIS
436
437 use Storable;
438 store \%table, 'file';
439 $hashref = retrieve('file');
440
441 use Storable qw(nstore store_fd nstore_fd freeze thaw dclone);
442
443 # Network order
444 nstore \%table, 'file';
445 $hashref = retrieve('file'); # There is NO nretrieve()
446
447 # Storing to and retrieving from an already opened file
448 store_fd \@array, \*STDOUT;
449 nstore_fd \%table, \*STDOUT;
9e21b3d0
JH
450 $aryref = fd_retrieve(\*SOCKET);
451 $hashref = fd_retrieve(\*SOCKET);
7a6a85bf
RG
452
453 # Serializing to memory
454 $serialized = freeze \%table;
455 %table_clone = %{ thaw($serialized) };
456
457 # Deep (recursive) cloning
458 $cloneref = dclone($ref);
459
dd19458b
JH
460 # Advisory locking
461 use Storable qw(lock_store lock_nstore lock_retrieve)
462 lock_store \%table, 'file';
463 lock_nstore \%table, 'file';
464 $hashref = lock_retrieve('file');
465
7a6a85bf
RG
466=head1 DESCRIPTION
467
f062ea6c 468The Storable package brings persistence to your Perl data structures
7a6a85bf 469containing SCALAR, ARRAY, HASH or REF objects, i.e. anything that can be
c261f00e 470conveniently stored to disk and retrieved at a later time.
7a6a85bf
RG
471
472It can be used in the regular procedural way by calling C<store> with
473a reference to the object to be stored, along with the file name where
474the image should be written.
775ecd75 475
7a6a85bf
RG
476The routine returns C<undef> for I/O problems or other internal error,
477a true value otherwise. Serious errors are propagated as a C<die> exception.
478
f062ea6c
PN
479To retrieve data stored to disk, use C<retrieve> with a file name.
480The objects stored into that file are recreated into memory for you,
481and a I<reference> to the root object is returned. In case an I/O error
7a6a85bf
RG
482occurs while reading, C<undef> is returned instead. Other serious
483errors are propagated via C<die>.
484
485Since storage is performed recursively, you might want to stuff references
486to objects that share a lot of common data into a single array or hash
487table, and then store that object. That way, when you retrieve back the
488whole thing, the objects will continue to share what they originally shared.
489
490At the cost of a slight header overhead, you may store to an already
491opened file descriptor using the C<store_fd> routine, and retrieve
9e21b3d0 492from a file via C<fd_retrieve>. Those names aren't imported by default,
c261f00e 493so you will have to do that explicitly if you need those routines.
7a6a85bf
RG
494The file descriptor you supply must be already opened, for read
495if you're going to retrieve and for write if you wish to store.
496
497 store_fd(\%table, *STDOUT) || die "can't store to stdout\n";
9e21b3d0 498 $hashref = fd_retrieve(*STDIN);
7a6a85bf
RG
499
500You can also store data in network order to allow easy sharing across
501multiple platforms, or when storing on a socket known to be remotely
502connected. The routines to call have an initial C<n> prefix for I<network>,
503as in C<nstore> and C<nstore_fd>. At retrieval time, your data will be
504correctly restored so you don't have to know whether you're restoring
dd19458b
JH
505from native or network ordered data. Double values are stored stringified
506to ensure portability as well, at the slight risk of loosing some precision
507in the last decimals.
7a6a85bf 508
9e21b3d0 509When using C<fd_retrieve>, objects are retrieved in sequence, one
7a6a85bf
RG
510object (i.e. one recursive tree) per associated C<store_fd>.
511
512If you're more from the object-oriented camp, you can inherit from
513Storable and directly store your objects by invoking C<store> as
514a method. The fact that the root of the to-be-stored tree is a
515blessed reference (i.e. an object) is special-cased so that the
516retrieve does not provide a reference to that object but rather the
517blessed object reference itself. (Otherwise, you'd get a reference
518to that blessed object).
519
520=head1 MEMORY STORE
521
522The Storable engine can also store data into a Perl scalar instead, to
523later retrieve them. This is mainly used to freeze a complex structure in
524some safe compact memory place (where it can possibly be sent to another
525process via some IPC, since freezing the structure also serializes it in
526effect). Later on, and maybe somewhere else, you can thaw the Perl scalar
527out and recreate the original complex structure in memory.
528
529Surprisingly, the routines to be called are named C<freeze> and C<thaw>.
530If you wish to send out the frozen scalar to another machine, use
531C<nfreeze> instead to get a portable image.
532
533Note that freezing an object structure and immediately thawing it
534actually achieves a deep cloning of that structure:
535
536 dclone(.) = thaw(freeze(.))
537
538Storable provides you with a C<dclone> interface which does not create
539that intermediary scalar but instead freezes the structure in some
c261f00e 540internal memory space and then immediately thaws it out.
7a6a85bf 541
dd19458b
JH
542=head1 ADVISORY LOCKING
543
f062ea6c
PN
544The C<lock_store> and C<lock_nstore> routine are equivalent to
545C<store> and C<nstore>, except that they get an exclusive lock on
546the file before writing. Likewise, C<lock_retrieve> does the same
547as C<retrieve>, but also gets a shared lock on the file before reading.
dd19458b 548
f062ea6c
PN
549As with any advisory locking scheme, the protection only works if you
550systematically use C<lock_store> and C<lock_retrieve>. If one side of
551your application uses C<store> whilst the other uses C<lock_retrieve>,
dd19458b
JH
552you will get no protection at all.
553
f062ea6c
PN
554The internal advisory locking is implemented using Perl's flock()
555routine. If your system does not support any form of flock(), or if
556you share your files across NFS, you might wish to use other forms
557of locking by using modules such as LockFile::Simple which lock a
558file using a filesystem entry, instead of locking the file descriptor.
dd19458b 559
7a6a85bf
RG
560=head1 SPEED
561
562The heart of Storable is written in C for decent speed. Extra low-level
4d3295e3
PN
563optimizations have been made when manipulating perl internals, to
564sacrifice encapsulation for the benefit of greater speed.
7a6a85bf
RG
565
566=head1 CANONICAL REPRESENTATION
567
f062ea6c 568Normally, Storable stores elements of hashes in the order they are
7a6a85bf
RG
569stored internally by Perl, i.e. pseudo-randomly. If you set
570C<$Storable::canonical> to some C<TRUE> value, Storable will store
571hashes with the elements sorted by their key. This allows you to
572compare data structures by comparing their frozen representations (or
573even the compressed frozen representations), which can be useful for
574creating lookup tables for complicated queries.
575
f062ea6c 576Canonical order does not imply network order; those are two orthogonal
7a6a85bf
RG
577settings.
578
d2b96869
SR
579=head1 CODE REFERENCES
580
581Since Storable version 2.05, CODE references may be serialized with
582the help of L<B::Deparse>. To enable this feature, set
3c4b39be 583C<$Storable::Deparse> to a true value. To enable deserialization,
d2b96869
SR
584C<$Storable::Eval> should be set to a true value. Be aware that
585deserialization is done through C<eval>, which is dangerous if the
586Storable file contains malicious data. You can set C<$Storable::Eval>
587to a subroutine reference which would be used instead of C<eval>. See
588below for an example using a L<Safe> compartment for deserialization
589of CODE references.
590
197b90bc
SR
591If C<$Storable::Deparse> and/or C<$Storable::Eval> are set to false
592values, then the value of C<$Storable::forgive_me> (see below) is
593respected while serializing and deserializing.
594
c261f00e
NC
595=head1 FORWARD COMPATIBILITY
596
597This release of Storable can be used on a newer version of Perl to
f062ea6c 598serialize data which is not supported by earlier Perls. By default,
c261f00e 599Storable will attempt to do the right thing, by C<croak()>ing if it
775ecd75 600encounters data that it cannot deserialize. However, the defaults
f062ea6c 601can be changed as follows:
c261f00e
NC
602
603=over 4
604
605=item utf8 data
606
607Perl 5.6 added support for Unicode characters with code points > 255,
608and Perl 5.8 has full support for Unicode characters in hash keys.
609Perl internally encodes strings with these characters using utf8, and
610Storable serializes them as utf8. By default, if an older version of
611Perl encounters a utf8 value it cannot represent, it will C<croak()>.
612To change this behaviour so that Storable deserializes utf8 encoded
613values as the string of bytes (effectively dropping the I<is_utf8> flag)
614set C<$Storable::drop_utf8> to some C<TRUE> value. This is a form of
615data loss, because with C<$drop_utf8> true, it becomes impossible to tell
616whether the original data was the Unicode string, or a series of bytes
617that happen to be valid utf8.
618
619=item restricted hashes
620
f062ea6c
PN
621Perl 5.8 adds support for restricted hashes, which have keys
622restricted to a given set, and can have values locked to be read only.
623By default, when Storable encounters a restricted hash on a perl
624that doesn't support them, it will deserialize it as a normal hash,
625silently discarding any placeholder keys and leaving the keys and
626all values unlocked. To make Storable C<croak()> instead, set
627C<$Storable::downgrade_restricted> to a C<FALSE> value. To restore
628the default set it back to some C<TRUE> value.
c261f00e 629
e8189732
NC
630=item files from future versions of Storable
631
632Earlier versions of Storable would immediately croak if they encountered
633a file with a higher internal version number than the reading Storable
634knew about. Internal version numbers are increased each time new data
635types (such as restricted hashes) are added to the vocabulary of the file
636format. This meant that a newer Storable module had no way of writing a
f062ea6c 637file readable by an older Storable, even if the writer didn't store newer
e8189732
NC
638data types.
639
640This version of Storable will defer croaking until it encounters a data
641type in the file that it does not recognize. This means that it will
642continue to read files generated by newer Storable modules which are careful
643in what they write out, making it easier to upgrade Storable modules in a
644mixed environment.
645
646The old behaviour of immediate croaking can be re-instated by setting
f062ea6c 647C<$Storable::accept_future_minor> to some C<FALSE> value.
e8189732 648
c261f00e
NC
649=back
650
f062ea6c 651All these variables have no effect on a newer Perl which supports the
c261f00e
NC
652relevant feature.
653
7a6a85bf
RG
654=head1 ERROR REPORTING
655
656Storable uses the "exception" paradigm, in that it does not try to workaround
657failures: if something bad happens, an exception is generated from the
658caller's perspective (see L<Carp> and C<croak()>). Use eval {} to trap
659those exceptions.
660
661When Storable croaks, it tries to report the error via the C<logcroak()>
662routine from the C<Log::Agent> package, if it is available.
663
212e9bde
JH
664Normal errors are reported by having store() or retrieve() return C<undef>.
665Such errors are usually I/O errors (or truncated stream errors at retrieval).
666
7a6a85bf
RG
667=head1 WIZARDS ONLY
668
669=head2 Hooks
670
671Any class may define hooks that will be called during the serialization
672and deserialization process on objects that are instances of that class.
673Those hooks can redefine the way serialization is performed (and therefore,
c261f00e 674how the symmetrical deserialization should be conducted).
7a6a85bf
RG
675
676Since we said earlier:
677
678 dclone(.) = thaw(freeze(.))
679
680everything we say about hooks should also hold for deep cloning. However,
681hooks get to know whether the operation is a mere serialization, or a cloning.
682
683Therefore, when serializing hooks are involved,
684
685 dclone(.) <> thaw(freeze(.))
686
687Well, you could keep them in sync, but there's no guarantee it will always
688hold on classes somebody else wrote. Besides, there is little to gain in
f062ea6c 689doing so: a serializing hook could keep only one attribute of an object,
7a6a85bf
RG
690which is probably not what should happen during a deep cloning of that
691same object.
692
693Here is the hooking interface:
694
bbc7dcd2 695=over 4
7a6a85bf
RG
696
697=item C<STORABLE_freeze> I<obj>, I<cloning>
698
699The serializing hook, called on the object during serialization. It can be
700inherited, or defined in the class itself, like any other method.
701
702Arguments: I<obj> is the object to serialize, I<cloning> is a flag indicating
703whether we're in a dclone() or a regular serialization via store() or freeze().
704
705Returned value: A LIST C<($serialized, $ref1, $ref2, ...)> where $serialized
706is the serialized form to be used, and the optional $ref1, $ref2, etc... are
707extra references that you wish to let the Storable engine serialize.
708
709At deserialization time, you will be given back the same LIST, but all the
710extra references will be pointing into the deserialized structure.
711
712The B<first time> the hook is hit in a serialization flow, you may have it
713return an empty list. That will signal the Storable engine to further
714discard that hook for this class and to therefore revert to the default
715serialization of the underlying Perl data. The hook will again be normally
716processed in the next serialization.
717
718Unless you know better, serializing hook should always say:
719
720 sub STORABLE_freeze {
721 my ($self, $cloning) = @_;
722 return if $cloning; # Regular default serialization
723 ....
724 }
725
726in order to keep reasonable dclone() semantics.
727
728=item C<STORABLE_thaw> I<obj>, I<cloning>, I<serialized>, ...
729
730The deserializing hook called on the object during deserialization.
f062ea6c 731But wait: if we're deserializing, there's no object yet... right?
7a6a85bf
RG
732
733Wrong: the Storable engine creates an empty one for you. If you know Eiffel,
734you can view C<STORABLE_thaw> as an alternate creation routine.
735
736This means the hook can be inherited like any other method, and that
737I<obj> is your blessed reference for this particular instance.
738
739The other arguments should look familiar if you know C<STORABLE_freeze>:
740I<cloning> is true when we're part of a deep clone operation, I<serialized>
741is the serialized string you returned to the engine in C<STORABLE_freeze>,
742and there may be an optional list of references, in the same order you gave
743them at serialization time, pointing to the deserialized objects (which
744have been processed courtesy of the Storable engine).
745
212e9bde
JH
746When the Storable engine does not find any C<STORABLE_thaw> hook routine,
747it tries to load the class by requiring the package dynamically (using
748the blessed package name), and then re-attempts the lookup. If at that
749time the hook cannot be located, the engine croaks. Note that this mechanism
c261f00e 750will fail if you define several classes in the same file, but L<perlmod>
212e9bde
JH
751warned you.
752
f062ea6c 753It is up to you to use this information to populate I<obj> the way you want.
7a6a85bf
RG
754
755Returned value: none.
756
2f796f32
AMS
757=item C<STORABLE_attach> I<class>, I<cloning>, I<serialized>
758
759While C<STORABLE_freeze> and C<STORABLE_thaw> are useful for classes where
3c4b39be 760each instance is independent, this mechanism has difficulty (or is
2f796f32
AMS
761incompatible) with objects that exist as common process-level or
762system-level resources, such as singleton objects, database pools, caches
763or memoized objects.
764
765The alternative C<STORABLE_attach> method provides a solution for these
1e2a0f0b
RGS
766shared objects. Instead of C<STORABLE_freeze> --E<gt> C<STORABLE_thaw>,
767you implement C<STORABLE_freeze> --E<gt> C<STORABLE_attach> instead.
2f796f32
AMS
768
769Arguments: I<class> is the class we are attaching to, I<cloning> is a flag
770indicating whether we're in a dclone() or a regular de-serialization via
771thaw(), and I<serialized> is the stored string for the resource object.
772
773Because these resource objects are considered to be owned by the entire
774process/system, and not the "property" of whatever is being serialized,
775no references underneath the object should be included in the serialized
776string. Thus, in any class that implements C<STORABLE_attach>, the
777C<STORABLE_freeze> method cannot return any references, and C<Storable>
778will throw an error if C<STORABLE_freeze> tries to return references.
779
780All information required to "attach" back to the shared resource object
781B<must> be contained B<only> in the C<STORABLE_freeze> return string.
782Otherwise, C<STORABLE_freeze> behaves as normal for C<STORABLE_attach>
783classes.
784
785Because C<STORABLE_attach> is passed the class (rather than an object),
786it also returns the object directly, rather than modifying the passed
787object.
788
789Returned value: object of type C<class>
790
7a6a85bf
RG
791=back
792
793=head2 Predicates
794
c261f00e 795Predicates are not exportable. They must be called by explicitly prefixing
7a6a85bf
RG
796them with the Storable package name.
797
bbc7dcd2 798=over 4
7a6a85bf
RG
799
800=item C<Storable::last_op_in_netorder>
801
802The C<Storable::last_op_in_netorder()> predicate will tell you whether
803network order was used in the last store or retrieve operation. If you
804don't know how to use this, just forget about it.
805
806=item C<Storable::is_storing>
807
808Returns true if within a store operation (via STORABLE_freeze hook).
809
810=item C<Storable::is_retrieving>
811
f062ea6c 812Returns true if within a retrieve operation (via STORABLE_thaw hook).
7a6a85bf
RG
813
814=back
815
816=head2 Recursion
817
f062ea6c
PN
818With hooks comes the ability to recurse back to the Storable engine.
819Indeed, hooks are regular Perl code, and Storable is convenient when
820it comes to serializing and deserializing things, so why not use it
821to handle the serialization string?
7a6a85bf 822
f062ea6c 823There are a few things you need to know, however:
7a6a85bf 824
bbc7dcd2 825=over 4
7a6a85bf
RG
826
827=item *
828
829You can create endless loops if the things you serialize via freeze()
f062ea6c
PN
830(for instance) point back to the object we're trying to serialize in
831the hook.
7a6a85bf
RG
832
833=item *
834
835Shared references among objects will not stay shared: if we're serializing
836the list of object [A, C] where both object A and C refer to the SAME object
837B, and if there is a serializing hook in A that says freeze(B), then when
838deserializing, we'll get [A', C'] where A' refers to B', but C' refers to D,
839a deep clone of B'. The topology was not preserved.
840
841=back
842
843That's why C<STORABLE_freeze> lets you provide a list of references
844to serialize. The engine guarantees that those will be serialized in the
845same context as the other objects, and therefore that shared objects will
846stay shared.
847
848In the above [A, C] example, the C<STORABLE_freeze> hook could return:
849
850 ("something", $self->{B})
851
852and the B part would be serialized by the engine. In C<STORABLE_thaw>, you
853would get back the reference to the B' object, deserialized for you.
854
855Therefore, recursion should normally be avoided, but is nonetheless supported.
856
857=head2 Deep Cloning
858
f062ea6c 859There is a Clone module available on CPAN which implements deep cloning
7a6a85bf
RG
860natively, i.e. without freezing to memory and thawing the result. It is
861aimed to replace Storable's dclone() some day. However, it does not currently
862support Storable hooks to redefine the way deep cloning is performed.
863
0a0da639
JH
864=head1 Storable magic
865
866Yes, there's a lot of that :-) But more precisely, in UNIX systems
867there's a utility called C<file>, which recognizes data files based on
868their contents (usually their first few bytes). For this to work,
8b793558 869a certain file called F<magic> needs to taught about the I<signature>
0a0da639 870of the data. Where that configuration file lives depends on the UNIX
f062ea6c 871flavour; often it's something like F</usr/share/misc/magic> or
8b793558
JH
872F</etc/magic>. Your system administrator needs to do the updating of
873the F<magic> file. The necessary signature information is output to
f062ea6c
PN
874STDOUT by invoking Storable::show_file_magic(). Note that the GNU
875implementation of the C<file> utility, version 3.38 or later,
876is expected to contain support for recognising Storable files
877out-of-the-box, in addition to other kinds of Perl files.
0a0da639 878
d4b9b6e4
GA
879You can also use the following functions to extract the file header
880information from Storable images:
881
882=over
883
884=item $info = Storable::file_magic( $filename )
885
886If the given file is a Storable image return a hash describing it. If
887the file is readable, but not a Storable image return C<undef>. If
888the file does not exist or is unreadable then croak.
889
890The hash returned has the following elements:
891
892=over
893
894=item C<version>
895
896This returns the file format version. It is a string like "2.7".
897
898Note that this version number is not the same as the version number of
899the Storable module itself. For instance Storable v0.7 create files
900in format v2.0 and Storable v2.15 create files in format v2.7. The
901file format version number only increment when additional features
902that would confuse older versions of the module are added.
903
904Files older than v2.0 will have the one of the version numbers "-1",
905"0" or "1". No minor number was used at that time.
906
907=item C<version_nv>
908
909This returns the file format version as number. It is a string like
910"2.007". This value is suitable for numeric comparisons.
911
912The constant function C<Storable::BIN_VERSION_NV> returns a comparable
913number that represent the highest file version number that this
914version of Storable fully support (but see discussion of
915C<$Storable::accept_future_minor> above). The constant
916C<Storable::BIN_WRITE_VERSION_NV> function returns what file version
917is written and might be less than C<Storable::BIN_VERSION_NV> in some
c4a6f826 918configurations.
d4b9b6e4
GA
919
920=item C<major>, C<minor>
921
922This also returns the file format version. If the version is "2.7"
923then major would be 2 and minor would be 7. The minor element is
924missing for when major is less than 2.
925
926=item C<hdrsize>
927
928The is the number of bytes that the Storable header occupies.
929
930=item C<netorder>
931
932This is TRUE if the image store data in network order. This means
933that it was created with nstore() or similar.
934
935=item C<byteorder>
936
937This is only present when C<netorder> is FALSE. It is the
938$Config{byteorder} string of the perl that created this image. It is
939a string like "1234" (32 bit little endian) or "87654321" (64 bit big
940endian). This must match the current perl for the image to be
941readable by Storable.
942
943=item C<intsize>, C<longsize>, C<ptrsize>, C<nvsize>
944
945These are only present when C<netorder> is FALSE. These are the sizes of
946various C datatypes of the perl that created this image. These must
947match the current perl for the image to be readable by Storable.
948
949The C<nvsize> element is only present for file format v2.2 and
950higher.
951
952=item C<file>
953
954The name of the file.
955
956=back
957
958=item $info = Storable::read_magic( $buffer )
959
960=item $info = Storable::read_magic( $buffer, $must_be_file )
961
962The $buffer should be a Storable image or the first few bytes of it.
963If $buffer starts with a Storable header, then a hash describing the
964image is returned, otherwise C<undef> is returned.
965
966The hash has the same structure as the one returned by
967Storable::file_magic(). The C<file> element is true if the image is a
968file image.
969
970If the $must_be_file argument is provided and is TRUE, then return
971C<undef> unless the image looks like it belongs to a file dump.
972
973The maximum size of a Storable header is currently 21 bytes. If the
974provided $buffer is only the first part of a Storable image it should
975at least be this long to ensure that read_magic() will recognize it as
976such.
977
978=back
979
7a6a85bf
RG
980=head1 EXAMPLES
981
982Here are some code samples showing a possible usage of Storable:
983
984 use Storable qw(store retrieve freeze thaw dclone);
985
986 %color = ('Blue' => 0.1, 'Red' => 0.8, 'Black' => 0, 'White' => 1);
987
2359510d 988 store(\%color, 'mycolors') or die "Can't store %a in mycolors!\n";
7a6a85bf 989
2359510d
SD
990 $colref = retrieve('mycolors');
991 die "Unable to retrieve from mycolors!\n" unless defined $colref;
7a6a85bf
RG
992 printf "Blue is still %lf\n", $colref->{'Blue'};
993
994 $colref2 = dclone(\%color);
995
996 $str = freeze(\%color);
997 printf "Serialization of %%color is %d bytes long.\n", length($str);
998 $colref3 = thaw($str);
999
1000which prints (on my machine):
1001
1002 Blue is still 0.100000
1003 Serialization of %color is 102 bytes long.
1004
d2b96869
SR
1005Serialization of CODE references and deserialization in a safe
1006compartment:
1007
197b90bc
SR
1008=for example begin
1009
d2b96869
SR
1010 use Storable qw(freeze thaw);
1011 use Safe;
1012 use strict;
1013 my $safe = new Safe;
197b90bc 1014 # because of opcodes used in "use strict":
d1e2299c 1015 $safe->permit(qw(:default require));
d2b96869
SR
1016 local $Storable::Deparse = 1;
1017 local $Storable::Eval = sub { $safe->reval($_[0]) };
197b90bc 1018 my $serialized = freeze(sub { 42 });
d2b96869 1019 my $code = thaw($serialized);
197b90bc
SR
1020 $code->() == 42;
1021
1022=for example end
1023
1024=for example_testing
1025 is( $code->(), 42 );
d2b96869 1026
7a6a85bf
RG
1027=head1 WARNING
1028
1029If you're using references as keys within your hash tables, you're bound
f062ea6c 1030to be disappointed when retrieving your data. Indeed, Perl stringifies
7a6a85bf
RG
1031references used as hash table keys. If you later wish to access the
1032items via another reference stringification (i.e. using the same
1033reference that was used for the key originally to record the value into
1034the hash table), it will work because both references stringify to the
1035same string.
1036
6fe6778b
PN
1037It won't work across a sequence of C<store> and C<retrieve> operations,
1038however, because the addresses in the retrieved objects, which are
1039part of the stringified references, will probably differ from the
1040original addresses. The topology of your structure is preserved,
1041but not hidden semantics like those.
7a6a85bf
RG
1042
1043On platforms where it matters, be sure to call C<binmode()> on the
1044descriptors that you pass to Storable functions.
1045
1046Storing data canonically that contains large hashes can be
1047significantly slower than storing the same data normally, as
c261f00e 1048temporary arrays to hold the keys for each hash have to be allocated,
7a6a85bf
RG
1049populated, sorted and freed. Some tests have shown a halving of the
1050speed of storing -- the exact penalty will depend on the complexity of
1051your data. There is no slowdown on retrieval.
1052
1053=head1 BUGS
1054
eda690a0 1055You can't store GLOB, FORMLINE, REGEXP, etc.... If you can define semantics
197b90bc
SR
1056for those operations, feel free to enhance Storable so that it can
1057deal with them.
7a6a85bf
RG
1058
1059The store functions will C<croak> if they run into such references
1060unless you set C<$Storable::forgive_me> to some C<TRUE> value. In that
1061case, the fatal message is turned in a warning and some
1062meaningless string is stored instead.
1063
1064Setting C<$Storable::canonical> may not yield frozen strings that
1065compare equal due to possible stringification of numbers. When the
f062ea6c 1066string version of a scalar exists, it is the form stored; therefore,
7a6a85bf
RG
1067if you happen to use your numbers as strings between two freezing
1068operations on the same data structures, you will get different
1069results.
1070
dd19458b
JH
1071When storing doubles in network order, their value is stored as text.
1072However, you should also not expect non-numeric floating-point values
1073such as infinity and "not a number" to pass successfully through a
1074nstore()/retrieve() pair.
1075
1076As Storable neither knows nor cares about character sets (although it
1077does know that characters may be more than eight bits wide), any difference
1078in the interpretation of character codes between a host and a target
1079system is your problem. In particular, if host and target use different
1080code points to represent the characters used in the text representation
1081of floating-point numbers, you will not be able be able to exchange
1082floating-point data, even with nstore().
1083
c261f00e
NC
1084C<Storable::drop_utf8> is a blunt tool. There is no facility either to
1085return B<all> strings as utf8 sequences, or to attempt to convert utf8
1086data back to 8 bit and C<croak()> if the conversion fails.
1087
ee0f7aac
NC
1088Prior to Storable 2.01, no distinction was made between signed and
1089unsigned integers on storing. By default Storable prefers to store a
1090scalars string representation (if it has one) so this would only cause
3c4b39be 1091problems when storing large unsigned integers that had never been converted
ee0f7aac
NC
1092to string or floating point. In other words values that had been generated
1093by integer operations such as logic ops and then not used in any string or
1094arithmetic context before storing.
1095
1096=head2 64 bit data in perl 5.6.0 and 5.6.1
1097
1098This section only applies to you if you have existing data written out
1099by Storable 2.02 or earlier on perl 5.6.0 or 5.6.1 on Unix or Linux which
1100has been configured with 64 bit integer support (not the default)
1101If you got a precompiled perl, rather than running Configure to build
1102your own perl from source, then it almost certainly does not affect you,
1103and you can stop reading now (unless you're curious). If you're using perl
1104on Windows it does not affect you.
1105
1106Storable writes a file header which contains the sizes of various C
1107language types for the C compiler that built Storable (when not writing in
1108network order), and will refuse to load files written by a Storable not
1109on the same (or compatible) architecture. This check and a check on
1110machine byteorder is needed because the size of various fields in the file
1111are given by the sizes of the C language types, and so files written on
1112different architectures are incompatible. This is done for increased speed.
1113(When writing in network order, all fields are written out as standard
1114lengths, which allows full interworking, but takes longer to read and write)
1115
1116Perl 5.6.x introduced the ability to optional configure the perl interpreter
1117to use C's C<long long> type to allow scalars to store 64 bit integers on 32
1118bit systems. However, due to the way the Perl configuration system
1119generated the C configuration files on non-Windows platforms, and the way
1120Storable generates its header, nothing in the Storable file header reflected
1121whether the perl writing was using 32 or 64 bit integers, despite the fact
1122that Storable was storing some data differently in the file. Hence Storable
1123running on perl with 64 bit integers will read the header from a file
1124written by a 32 bit perl, not realise that the data is actually in a subtly
1125incompatible format, and then go horribly wrong (possibly crashing) if it
1126encountered a stored integer. This is a design failure.
1127
1128Storable has now been changed to write out and read in a file header with
1129information about the size of integers. It's impossible to detect whether
1130an old file being read in was written with 32 or 64 bit integers (they have
1131the same header) so it's impossible to automatically switch to a correct
1132backwards compatibility mode. Hence this Storable defaults to the new,
1133correct behaviour.
1134
1135What this means is that if you have data written by Storable 1.x running
1136on perl 5.6.0 or 5.6.1 configured with 64 bit integers on Unix or Linux
1137then by default this Storable will refuse to read it, giving the error
1138I<Byte order is not compatible>. If you have such data then you you
1139should set C<$Storable::interwork_56_64bit> to a true value to make this
1140Storable read and write files with the old header. You should also
1141migrate your data, or any older perl you are communicating with, to this
1142current version of Storable.
1143
1144If you don't have data written with specific configuration of perl described
1145above, then you do not and should not do anything. Don't set the flag -
1146not only will Storable on an identically configured perl refuse to load them,
1147but Storable a differently configured perl will load them believing them
1148to be correct for it, and then may well fail or crash part way through
1149reading them.
1150
7a6a85bf
RG
1151=head1 CREDITS
1152
1153Thank you to (in chronological order):
1154
1155 Jarkko Hietaniemi <jhi@iki.fi>
1156 Ulrich Pfeifer <pfeifer@charly.informatik.uni-dortmund.de>
51f77169 1157 Benjamin A. Holzman <bholzman@earthlink.net>
7a6a85bf
RG
1158 Andrew Ford <A.Ford@ford-mason.co.uk>
1159 Gisle Aas <gisle@aas.no>
1160 Jeff Gresham <gresham_jeffrey@jpmorgan.com>
1161 Murray Nesbitt <murray@activestate.com>
1162 Marc Lehmann <pcg@opengroup.org>
9e21b3d0
JH
1163 Justin Banks <justinb@wamnet.com>
1164 Jarkko Hietaniemi <jhi@iki.fi> (AGAIN, as perl 5.7.0 Pumpkin!)
dd19458b
JH
1165 Salvador Ortiz Garcia <sog@msg.com.mx>
1166 Dominic Dunlop <domo@computer.org>
1167 Erik Haugan <erik@solbors.no>
51f77169 1168 Benjamin A. Holzman <ben.holzman@grantstreet.com>
7a6a85bf
RG
1169
1170for their bug reports, suggestions and contributions.
1171
1172Benjamin Holzman contributed the tied variable support, Andrew Ford
1173contributed the canonical order for hashes, and Gisle Aas fixed
f062ea6c 1174a few misunderstandings of mine regarding the perl internals,
7a6a85bf
RG
1175and optimized the emission of "tags" in the output streams by
1176simply counting the objects instead of tagging them (leading to
1177a binary incompatibility for the Storable image starting at version
f062ea6c 11780.6--older images are, of course, still properly understood).
7a6a85bf 1179Murray Nesbitt made Storable thread-safe. Marc Lehmann added overloading
51f77169
AMS
1180and references to tied items support. Benjamin Holzman added a performance
1181improvement for overloaded classes; thanks to Grant Street Group for footing
1182the bill.
7a6a85bf 1183
7a6a85bf
RG
1184=head1 AUTHOR
1185
0ba8809e 1186Storable was written by Raphael Manfredi F<E<lt>Raphael_Manfredi@pobox.comE<gt>>
775ecd75 1187Maintenance is now done by the perl5-porters F<E<lt>perl5-porters@perl.orgE<gt>>
0ba8809e
NC
1188
1189Please e-mail us with problems, bug fixes, comments and complaints,
d119459b 1190although if you have compliments you should send them to Raphael.
0ba8809e
NC
1191Please don't e-mail Raphael with problems, as he no longer works on
1192Storable, and your message will be delayed while he forwards it to us.
7a6a85bf
RG
1193
1194=head1 SEE ALSO
1195
c261f00e 1196L<Clone>.
7a6a85bf
RG
1197
1198=cut