How to 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 have 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 can I turn it into text, and then when I need it, return to the array of array references?

+4
source share
3 answers

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

The JSON module is fast enough and efficient (if you install JSON :: XS from cpan, it will compile a version of C for you, and use JSON will automatically use this).

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

I also used Storable . I donโ€™t like it - the interface is strange, and the conclusion is meaningless, and this is a proprietary format. Data::Dumper is fast and readable, but in fact it should be one-way ( eval ing a bit hacky), and again, this is just Perl. I also rode myself. In the end, I came to the conclusion that JSON is the best, fast, flexible and reliable.

+4
source

You can topple over on your own, but you need to worry about complex issues such as escaping quotes and backslashes or selected delimiters.

The program below shows how you can use the standard Perl Data :: Dumper and Storable modules to serialize and deserialize data in a way that is suitable for storage 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 :: A dumper has the nice property of being human-readable, but a serious flaw requires eval deserialization. Storage is good and compact, but not transparent.

+1
source

All Articles