简体   繁体   中英

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

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?

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 ( eval ing 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM