dax*_*xim 21
您正在寻找数据序列化.强大的热门选择是Sereal,JSON :: XS和YAML :: XS.鲜为人知的格式有:ASN.1,Avro,BERT,BSON,CBOR,JSYNC,MessagePack,Protocol Buffers,Thrift.
其他经常提到的选择是Storable和Data :: Dumper(或类似)/ eval,但我不推荐它们,因为Storable的格式依赖于Perl版本,并且eval因为它执行任意代码而不安全.截至2012年,解析对应部分Data :: Undump还没有取得很大进展.我也不建议使用XML,因为它没有很好地映射Perl数据类型,并且存在多个竞争/不兼容的模式如何在XML和数据之间进行转换.
代码示例(已测试):
use JSON::XS qw(encode_json decode_json);
use File::Slurp qw(read_file write_file);
my %hash;
{
my $json = encode_json \%hash;
write_file('dump.json', { binmode => ':raw' }, $json);
}
{
my $json = read_file('dump.json', { binmode => ':raw' });
%hash = %{ decode_json $json };
}
Run Code Online (Sandbox Code Playgroud)
use YAML::XS qw(Load Dump);
use File::Slurp qw(read_file write_file);
my %hash;
{
my $yaml = Dump \%hash;
write_file('dump.yml', { binmode => ':raw' }, $yaml);
}
{
my $yaml = read_file('dump.yml', { binmode => ':raw' });
%hash = %{ Load $yaml };
}
Run Code Online (Sandbox Code Playgroud)
从这里开始的下一步是对象持久性.