对于Perl的数据序列化,有很多模块可供选择,我不知道该选哪一个。
我有以下需要序列化为字符串以便放入数据库的数据:
my @categories = (
["Education", "Higher Education", "Colleges"],
["Schooling", "Colleges"]
);
我该如何把它转换成文本,然后在需要的时候再将其转换回数组的数组引用?
对于Perl的数据序列化,有很多模块可供选择,我不知道该选哪一个。
我有以下需要序列化为字符串以便放入数据库的数据:
my @categories = (
["Education", "Higher Education", "Colleges"],
["Schooling", "Colleges"]
);
我该如何把它转换成文本,然后在需要的时候再将其转换回数组的数组引用?
你可以自己编写代码,但是需要考虑到一些棘手的问题,例如转义引号和反斜杠或者所选择的分隔符。
下面的程序展示了如何使用标准的Perl模块Data::Dumper和Storable来序列化和反序列化数据,以适合存储在数据库中。
#! /usr/bin/env perl
use strict;
use warnings;
use Data::Dumper;
use Storable qw/ nfreeze thaw /;
use Test::More tests => 2;
my @categories = (
["Education", "Higher Education", "Colleges"],
["Schooling", "Colleges"]
);
{
local $Data::Dumper::Indent = 0;
local $Data::Dumper::Terse = 1;
my $serialized = Dumper \@categories;
print $serialized, "\n";
my $restored = eval($serialized) || die "deserialization failed: $@";
is_deeply $restored, \@categories;
}
{
my $serialized = unpack "H*", nfreeze \@categories;
print $serialized, "\n";
my $restored = thaw pack "H*", $serialized;
die "deserialization failed: $@" unless defined $restored;
is_deeply $restored, \@categories;
}
Data::Dumper有一个好处,就是易于人类阅读,但严重的缺点是需要使用eval
进行反序列化。Storable则是紧凑而不透明的。