How do I serialize an array of array-references in Perl?

穿精又带淫゛_ 提交于 2020-01-14 10:43:36

问题


There are so many modules for serializing data for Perl, and I don't know which one to choose.

I've the following data that I need to serialize as a string so I can put it in the database:

my @categories = (
    ["Education", "Higher Education", "Colleges"],
    ["Schooling", "Colleges"]
);

How could I turn it into text, and then later when I need it, turn back into an array of array-references?


回答1:


I vote for JSON (or Data::Serializer as mentioned in another answer, in conjunction with JSON).

The JSON module is plenty fast and efficient (if you install JSON::XS from cpan, it will compile the C version for you, and use JSON will automatically use that).

It works great with Perl data structures, is standardized, and the Javascript syntax is so similar to Perl syntax. There are options you can set with the JSON module to improve human readability (linebreaks, etc.)

I've also used Storable. I don't like it--the interface is weird, and the output is nonsensical, and it is a proprietary format. Data::Dumper is fast and quite readable but is really meant to be one-way (evaling it is slightly hackish), and again, it's Perl only. I've also rolled my own as well. In the end, I concluded JSON is the best, is fast, flexible, and robust.




回答2:


You can use Data::Serializer:

  • Examples/Information from OnPerl.net

  • Data::Serializer Module from CPAN




回答3:


You could roll your own, but you have to worry about tricky issues such as escaping quotes and backslashes or the separators you choose.

The program below shows how you can use standard Perl modules Data::Dumper and Storable to serialize and deserialize your data in a way that is suitable for storing in a database.

#! /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 has the nice property of being human readable, but the severe negative of requiring eval to deserialize. Storable is nice and compact but opaque.



来源:https://stackoverflow.com/questions/11092658/how-do-i-serialize-an-array-of-array-references-in-perl

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!