Simple, modern, robust, transparent persistence of data structures for Perl

风流意气都作罢 提交于 2019-12-04 00:27:23

To achieve your "transparency" goal, you're going to have to either abstract it into a framework (as chambwez suggested) or use tied variables which will save themselves to disk whenever they're updated. DBM hashes use tie in this way, so DBM::Deep is probably your best bet; everything else I'm aware of requires you to explicitly tell it when to write data out and/or caches writes in the name of performance.

Zoran Simic

Why not use JSON? It's rather easy (unless I misunderstood your question), all you would do is this:

use JSON;
# serialize to file
open(my $fh, ">myfile");
print $fh encode_json($ds); 
close $fh;
# deserialize from file
open(my $fh, "<myfile");
local $/ = undef;
my $content = <$fh>;
$ds = decode_json($content);
close $fh;

Another easy thing you can do is use Data::Dumper.

I don't think transparent persistence is very good idea. Suppose you have hypothetical implementation that ties perl data structure to outside world. To be transparent, every write into the structure have to be detected and data outside updated. This is probably going to be quite expensive and end with a lot of disk activity unless you have sophisticated backend with fast random access. I cannot imagine updates of JSON file be efficient.

Some options:

  • use database backend (DBM::Deep, DB_File or KiokuDB)
  • use key-value store as backend (Memcached, Redis)
  • define consistent workflow on data and serialize/deserialize in good moment
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!