存储和Perl中读入文件的哈希和数组 [英] Store and read hash and array in files in Perl

查看:305
本文介绍了存储和Perl中读入文件的哈希和数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是一个noob.I需要有关数据应该如何保存,并在perl的阅读一些基本知识。说救哈希和数组。是什么格式的文件(扩展名)应该使用?文本?到目前为止,我只能保存所有东西串打印文件%哈希并阅读他们回来为字符串打印<文件> 。我应该怎么做,如果我需要我的散列函数和阵列输入从文件。如何把他们带回哈希和阵列?

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 ,< A HREF =htt​​p://jsync.org/相对=nofollow> JSYNC , MessagePack Protocol Buffers的,的节俭

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.

其他经常提到的选择是可保存并的数据::自卸车(或类似)/ 评估,但我不能建议他们,因为可存储的格式是Perl版本依赖,和评估是不安全的,因为它执行任意code。截至2012年,解析反一部分数据:: 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.

code例子(测试):

Code examples (tested):

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆