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