Saving Data Structures
If 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.
use Data::Dumper; $Data::Dumper::Purity = 1; # since %TV is self–referential open (FILE, "> tvinfo.perldata") || die "can't open tvinfo: $!"; print FILE Data::Dumper–>Dump([\%TV], ['*TV']); close(FILE) || die "can't close tvinfo: $!";
A separate program (or the same program) can then read in the file later:
open (FILE, "< tvinfo.perldata") || 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) || die "can't close tvinfo: $!";
print $TV{simpsons}{members}[2]{age};or simply:
do "tvinfo.perldata" || die "can't recreate tvinfo: $! $@";
print $TV{simpsons}{members}[2]{age};Storable, another standard module, writes out data structures in
very fast, packed binary format. It also supports automatic file
locking (provided your system implements the flock function), and it even has fancy hooks
so object classes can handle their own serialization. Here’s how you
might save that same structure using Storable:
use Storable qw(lock_nstore); lock_nstore(\%TV, "tvdata.storable");
And here’s how to restore it into a variable that will hold a reference to the retrieved hash: ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access