我是个新手,需要了解如何在Perl下保存和读取数据的基础知识,比如如何保存哈希表和数组。应该使用什么文件格式(扩展名)?txt格式可以吗?目前我只能将所有东西以字符串形式保存print FILE %hash
,并将它们作为字符串读取回来print <FILE>
。如果我需要从文件中获取哈希表和数组输入,我该怎么做?如何将它们放回哈希表和数组中?
我是个新手,需要了解如何在Perl下保存和读取数据的基础知识,比如如何保存哈希表和数组。应该使用什么文件格式(扩展名)?txt格式可以吗?目前我只能将所有东西以字符串形式保存print FILE %hash
,并将它们作为字符串读取回来print <FILE>
。如果我需要从文件中获取哈希表和数组输入,我该怎么做?如何将它们放回哈希表和数组中?
您正在寻找数据序列化。流行的选择包括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 };
}
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代码,使您能够将文件读入数组或将哈希写回文件。
#Load a file into a hash.
#My Text file has the following format.
#field1=value1
#field2=value2
#<FILE1> is an opens a sample txt file in read-only mode.
my %hash;
while (<FILE1>)
{
chomp;
my ($key, $val) = split /=/;
$hash{$key} .= exists $hash{$key} ? ",$val" : $val;
}