home *** CD-ROM | disk | FTP | other *** search
/ CD Actual Thematic 7: Programming / CDAT7.iso / Share / Editores / Perl5 / perl / lib / site / Storable.pm < prev    next >
Encoding:
Text File  |  1997-08-10  |  10.7 KB  |  346 lines

  1. ;# $Id: Storable.pm,v 0.5 1997/06/10 16:38:37 ram Exp $
  2. ;#
  3. ;#  Copyright (c) 1995-1997, Raphael Manfredi
  4. ;#  
  5. ;#  You may redistribute only under the terms of the Artistic License,
  6. ;#  as specified in the README file that comes with the distribution.
  7. ;#
  8. ;# $Log: Storable.pm,v $
  9. ;# Revision 0.5  1997/06/10  16:38:37  ram
  10. ;# Baseline for fifth alpha release.
  11. ;#
  12.  
  13. require DynaLoader;
  14. require Exporter;
  15. package Storable; @ISA = qw(Exporter DynaLoader);
  16.  
  17. @EXPORT = qw(store retrieve);
  18. @EXPORT_OK = qw(
  19.     nstore store_fd nstore_fd retrieve_fd
  20.     freeze nfreeze thaw
  21.     dclone
  22. );
  23.  
  24. use AutoLoader;
  25. use Carp;
  26. use vars qw($forgive_me $VERSION);
  27.  
  28. $VERSION = '0.5';
  29. *AUTOLOAD = \&AutoLoader::AUTOLOAD;        # Grrr...
  30.  
  31. bootstrap Storable;
  32. 1;
  33. __END__
  34.  
  35. #
  36. # store
  37. #
  38. # Store target object hierarchy, identified by a reference to its root.
  39. # The stored object tree may later be retrieved to memory via retrieve.
  40. # Returns undef if an I/O error occurred, in which case the file is
  41. # removed.
  42. #
  43. sub store {
  44.     return _store(0, @_);
  45. }
  46.  
  47. #
  48. # nstore
  49. #
  50. # Same as store, but in network order.
  51. #
  52. sub nstore {
  53.     return _store(1, @_);
  54. }
  55.  
  56. # Internal store to file routine
  57. sub _store {
  58.     my $netorder = shift;
  59.     my $self = shift;
  60.     my ($file) = @_;
  61.     croak "Not a reference" unless ref($self);
  62.     croak "Too many arguments" unless @_ == 1;    # Watch out for @foo in arglist
  63.     local *FILE;
  64.     open(FILE, ">$file") || croak "Can't create $file: $!";
  65.     binmode FILE;
  66.     my $ret;
  67.     # Call C routine nstore or pstore, depending on network order
  68.     eval { $ret = $netorder ? net_pstore(FILE, $self) : pstore(FILE, $self) };
  69.     close(FILE) or $ret = undef;
  70.     unlink($file) or warn "Can't unlink $file: $!\n" if $@ || !defined $ret;
  71.     croak $@ if $@ =~ s/\.?\n$/,/;
  72.     return $ret ? $ret : undef;
  73. }
  74.  
  75. #
  76. # store_fd
  77. #
  78. # Same as store, but perform on an already opened file descriptor instead.
  79. # Returns undef if an I/O error occurred.
  80. #
  81. sub store_fd {
  82.     return _store_fd(0, @_);
  83. }
  84.  
  85. #
  86. # nstore_fd
  87. #
  88. # Same as store_fd, but in network order.
  89. #
  90. sub nstore_fd {
  91.     my ($self, $file) = @_;
  92.     return _store_fd(1, @_);
  93. }
  94.  
  95. # Internal store routine on opened file descriptor
  96. sub _store_fd {
  97.     my $netorder = shift;
  98.     my $self = shift;
  99.     my ($file) = @_;
  100.     croak "Not a reference" unless ref($self);
  101.     croak "Too many arguments" unless @_ == 1;    # Watch out for @foo in arglist
  102.     my $fd = fileno($file);
  103.     croak "Not a valid file descriptor" unless defined $fd;
  104.     my $ret;
  105.     # Call C routine nstore or pstore, depending on network order
  106.     eval { $ret = $netorder ? net_pstore($file, $self) : pstore($file, $self) };
  107.     croak $@ if $@ =~ s/\.?\n$/,/;
  108.     return $ret ? $ret : undef;
  109. }
  110.  
  111. #
  112. # freeze
  113. #
  114. # Store oject and its hierarchy in memory and return a scalar
  115. # containing the result.
  116. #
  117. sub freeze {
  118.     _freeze(0, @_);
  119. }
  120.  
  121. #
  122. # nfreeze
  123. #
  124. # Same as freeze but in network order.
  125. #
  126. sub nfreeze {
  127.     _freeze(1, @_);
  128. }
  129.  
  130. # Internal freeze routine
  131. sub _freeze {
  132.     my $netorder = shift;
  133.     my $self = shift;
  134.     croak "Not a reference" unless ref($self);
  135.     croak "Too many arguments" unless @_ == 0;    # Watch out for @foo in arglist
  136.     my $ret;
  137.     # Call C routine mstore or net_mstore, depending on network order
  138.     eval { $ret = $netorder ? net_mstore($self) : mstore($self) };
  139.     croak $@ if $@ =~ s/\.?\n$/,/;
  140.     return $ret ? $ret : undef;
  141. }
  142. #
  143. # retrieve
  144. #
  145. # Retrieve object hierarchy from disk, returning a reference to the root
  146. # object of that tree.
  147. #
  148. sub retrieve {
  149.     my ($file) = @_;
  150.     local *FILE;
  151.     open(FILE, "$file") || croak "Can't open $file: $!";
  152.     binmode FILE;
  153.     my $self;
  154.     eval { $self = pretrieve(FILE) };        # Call C routine
  155.     close(FILE);
  156.     croak $@ if $@ =~ s/\.?\n$/,/;
  157.     return $self;
  158. }
  159.  
  160. #
  161. # retrieve_fd
  162. #
  163. # Same as retrieve, but perform from an already opened file descriptor instead.
  164. #
  165. sub retrieve_fd {
  166.     my ($file) = @_;
  167.     my $fd = fileno($file);
  168.     croak "Not a valid file descriptor" unless defined $fd;
  169.     my $self;
  170.     eval { $self = pretrieve($file) };        # Call C routine
  171.     croak $@ if $@ =~ s/\.?\n$/,/;
  172.     return $self;
  173. }
  174.  
  175. #
  176. # thaw
  177. #
  178. # Recreate objects in memory from an existing frozen image created
  179. # by freeze.
  180. #
  181. sub thaw {
  182.     my ($frozen) = @_;
  183.     my $self;
  184.     eval { $self = mretrieve($frozen) };    # Call C routine
  185.     croak $@ if $@ =~ s/\.?\n$/,/;
  186.     return $self;
  187. }
  188.  
  189. =head1 NAME
  190.  
  191. Storable - persistency for perl data structures
  192.  
  193. =head1 SYNOPSIS
  194.  
  195.     use Storable;
  196.     store \%table, 'file';
  197.     $hashref = retrieve('file');
  198.  
  199. =head1 DESCRIPTION
  200.  
  201. The Storable package brings you persistency for your perl data structures
  202. containing SCALAR, ARRAY, HASH or REF objects, i.e. anything that can be
  203. convenientely stored to disk and retrieved at a later time.
  204.  
  205. It can be used in the regular procedural way by calling C<store> with
  206. a reference to the object to store, and providing a file name. The routine
  207. returns C<undef> for I/O problems or other internal error, a true value
  208. otherwise. Serious errors are propagated as a C<die> exception.
  209.  
  210. To retrieve data stored to disk, you use C<retrieve> with a file name,
  211. and the objects stored into that file are recreated into memory for you,
  212. and a I<reference> to the root object is returned. In case an I/O error
  213. occurred while reading, C<undef> is returned instead. Other serious
  214. errors are propagated via C<die>.
  215.  
  216. Since storage is performed recursively, you might want to stuff references
  217. to objects that share a lot of common data into a single array or hash
  218. table, and then store that object. That way, when you retrieve back the
  219. whole thing, the objects will continue to share what they originally shared.
  220.  
  221. At the cost of a slight header overhead, you may store to an already
  222. opened file descriptor using the C<store_fd> routine, and retrieve
  223. from a file via C<retrieve_fd>. Those names aren't imported by default,
  224. so you will have to do that explicitely if you need those routines.
  225. The file descriptor name you supply must be fully qualified.
  226.  
  227. You can also store data in network order to allow easy sharing across
  228. multiple platforms, or when storing on a socket known to be remotely
  229. connected. The routines to call have an initial C<n> prefix for I<network>,
  230. as in C<nstore> and C<nstore_fd>. At retrieval time, your data will be
  231. correctly restored so you don't have to know whether you're restoring
  232. from native or network ordered data.
  233.  
  234. When using C<retrieve_fd>, objects are retrieved in sequence, one
  235. object (i.e. one recursive tree) per associated C<store_fd>.
  236.  
  237. If you're more from the object-oriented camp, you can inherit from
  238. Storable and directly store your objects by invoking C<store> as
  239. a method. The fact that the root of the to-be-stored tree is a
  240. blessed reference (i.e. an object) is special-cased so that the
  241. retrieve does not provide a reference to that object but rather the
  242. blessed object reference itself. (Otherwise, you'd get a reference
  243. to that blessed object).
  244.  
  245. =head1 MEMORY STORE
  246.  
  247. The Storable engine can also store data into a Perl scalar instead, to
  248. later retrieve them. This is mainly used to freeze a complex structure in
  249. some safe compact memory place (where it can possibly be sent to another
  250. process via some IPC, since freezing the structure also serializes it in
  251. effect). Later on, and maybe somewhere else, you can thaw the Perl scalar
  252. out and recreate the original complex structure in memory.
  253.  
  254. Surprisingly, the routines to be called are named C<freeze> and C<thaw>.
  255. If you wish to send out the frozen scalar to another machine, use
  256. C<nfreeze> instead to get a portable image.
  257.  
  258. Note that freezing an object structure and immediately thawing it
  259. actually achieves a deep cloning of that structure. Storable provides
  260. you with a C<dclone> interface which does not create that intermediary
  261. scalar but instead freezes the structure in some internal memory space
  262. and then immediatly thaws it out.
  263.  
  264. =head1 SPEED
  265.  
  266. The heart of Storable is written in C for decent speed. Extra low-level
  267. optimization have been made when manipulating perl internals, to
  268. sacrifice encapsulation for the benefit of a greater speed.
  269.  
  270. Storage is usually faster than retrieval since the latter has to
  271. allocate the objects from memory and perform the relevant I/Os, whilst
  272. the former mainly performs I/Os.
  273.  
  274. On my HP 9000/712 machine running HPUX 9.03 and with perl 5.004, I can
  275. store 0.8 Mbyte/s and I can retrieve at 0.72 Mbytes/s, approximatively
  276. (CPU + system time).
  277. This was measured with Benchmark and the I<Magic: The Gathering>
  278. database from Tom Christiansen (1.9 Mbytes).
  279.  
  280. =head1 EXAMPLES
  281.  
  282. Here are some code samples showing a possible usage of Storable:
  283.  
  284.     use Storable qw(store retrieve freeze thaw dclone);
  285.  
  286.     %color = ('Blue' => 0.1, 'Red' => 0.8, 'Black' => 0, 'White' => 1);
  287.  
  288.     store(\%color, '/tmp/colors') or die "Can't store %a in /tmp/colors!\n";
  289.  
  290.     $colref = retrieve('/tmp/colors');
  291.     die "Unable to retrieve from /tmp/colors!\n" unless defined $colref;
  292.     printf "Blue is still %lf\n", $colref->{'Blue'};
  293.  
  294.     $colref2 = dclone(\%color);
  295.  
  296.     $str = freeze(\%color);
  297.     printf "Serialization of %%color is %d bytes long.\n", length($str);
  298.     $colref3 = thaw($str);
  299.  
  300. which prints (on my machine):
  301.  
  302.     Blue is still 0.100000
  303.     Serialization of %color is 102 bytes long.
  304.  
  305. =head1 WARNING
  306.  
  307. If you're using references as keys within your hash tables, you're bound
  308. to disapointment when retrieving your data. Indeed, Perl stringifies
  309. references used as hash table keys. If you later wish to access the
  310. items via another reference stringification (i.e. using the same
  311. reference that was used for the key originally to record the value into
  312. the hash table), it will work because both references stringify to the
  313. same string.
  314.  
  315. It won't work across a C<store> and C<retrieve> operations however, because
  316. the addresses in the retrieved objects, which are part of the stringified
  317. references, will probably differ from the original addresses. The
  318. topology of your structure is preserved, but not hidden semantics
  319. like those.
  320.  
  321. On platforms where it matters, be sure to call C<binmode()> on the
  322. descriptors that you pass to Storable functions.
  323.  
  324. =head1 BUGS
  325.  
  326. You can't store GLOB, CODE, FORMLINE, etc... If you can define
  327. semantics for those operations, feel free to enhance Storable so that
  328. it can deal with those.
  329.  
  330. The store functions will C<croak> if they run into such references
  331. unless you set C<$Storable::forgive_me> to some C<TRUE> value. In this
  332. case, the fatal message is turned in a warning and some
  333. meaningless string is stored instead.
  334.  
  335. Due to the aforementionned optimizations, Storable is at the mercy
  336. of perl's internal redesign or structure changes. If that bothers
  337. you, you can try convincing Larry that what is used in Storable
  338. should be documented and consistently kept in future revisions.
  339. As I said, you may try.
  340.  
  341. =head1 AUTHOR
  342.  
  343. Raphael Manfredi F<E<lt>Raphael_Manfredi@grenoble.hp.comE<gt>>
  344.  
  345. =cut
  346.