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