9.7. Saving Data StructuresIf you want to save your data structures for use by another program later, there are many ways to do it. The easiest way is to use Perl's Data::Dumper module, which turns a (possibly self-referential) data structure into a string that can be saved externally and later reconstituted with eval or do. A separate program (or the same program) can then read in the file later:use Data::Dumper; $Data::Dumper::Purity = 1; # since %TV is self-referential open (FILE, "> tvinfo.perldata") or die "can't open tvinfo: $!"; print FILE Data::Dumper->Dump([\%TV], ['*TV']); close FILE or die "can't close tvinfo: $!"; or simply:open (FILE, "< tvinfo.perldata") or die "can't open tvinfo: $!"; undef $/; # read in file all at once eval <FILE>; # recreate %TV die "can't recreate tv data from tvinfo.perldata: $@" if $@; close FILE or die "can't close tvinfo: $!"; print $TV{simpsons}{members}[2]{age}; Many other solutions are available, with storage formats ranging from packed binary (very fast) to XML (very interoperable). Check out a CPAN mirror near you today!do "tvinfo.perldata" or die "can't recreate tvinfo: $! $@"; print $TV{simpsons}{members}[2]{age}; Copyright © 2002 O'Reilly & Associates. All rights reserved. |
|