在 Perl 中的文件中存储和读取哈希和数组 [英] Store and read hash and array in files in Perl
问题描述
我是菜鸟.我需要一些关于如何在 perl 下保存和读取数据的基本知识.说要保存一个散列和一个数组.应该使用什么格式(扩展名)的文件?文本?到目前为止,我只能将所有内容保存为 stringprint FILE %hash
并将它们读回为 stringprint
.如果我需要来自文件的函数散列和数组输入,我该怎么办.如何将它们放回散列和数组?
I'm a noob.I need some basic knowledge about how data should be saved and read under perl. Say to save a hash and an array. What format (extension) of file should be used? txt? So far I can only save all the things as stringprint FILE %hash
and read them back as stringprint <FILE>
. What should I do if I need my function hash and array inputs from a file. How to put them back to hash and array?
推荐答案
您正在寻找数据序列化.强大的流行选择是 Sereal、JSON::XS 和 YAML::XS.鲜为人知的格式有:ASN.1、Avro、BERT、BSON, CBOR、JSYNC、MessagePack、协议缓冲区、节俭.
You're looking for data serialisation. Popular choices that are robust are Sereal, JSON::XS and YAML::XS. Lesser known formats are: ASN.1, Avro, BERT, BSON, CBOR, JSYNC, MessagePack, Protocol Buffers, Thrift.
其他经常提到的选择是 Storable 和 Data::Dumper(或类似的)/eval
,但我不能推荐它们,因为 Storable 的格式取决于 Perl 版本,并且 eval
是不安全的,因为它执行任意代码.截至 2012 年,解析计数器部分 Data::Undump 还没有取得很大进展.我也不推荐使用 XML,因为它不能很好地映射 Perl 数据类型,并且存在多个相互竞争/不兼容的模式如何在 XML 和数据之间进行转换.
Other often mentioned choices are Storable and Data::Dumper (or similar)/eval
, but I cannot recommend them because Storable's format is Perl version dependent, and eval
is unsafe because it executes arbitrary code. As of 2012, the parsing counter-part Data::Undump has not progressed very far yet. I also cannot recommend using XML because it does not map Perl data types well, and there exists multiple competing/incompatible schemas how to translate between XML and data.
代码示例(已测试):
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 };
}
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 };
}
从这里开始的下一步是对象持久性.
另请阅读:Perl 序列化程序:何时使用什么
这篇关于在 Perl 中的文件中存储和读取哈希和数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!