Data Formats

40.1 JSON

use v5.36;
use JSON::PP;                         # core; JSON::MaybeXS / Cpanel::JSON::XS are faster
my $json = JSON::PP->new->utf8->canonical->pretty;
my $data = $json->decode('{"name":"Ana","tags":["perl","sql"],"active":true}');
say $data->{tags}[0];
say $data->{active} ? 'active' : 'inactive';   # JSON booleans become JSON::PP::Boolean objects
my $text = $json->encode({ name => 'Bo', scores => [90, 85], admin => JSON::PP::true });
use JSON::MaybeXS qw(encode_json decode_json);     # picks the fastest available backend

40.2 YAML

use YAML::XS qw(LoadFile DumpFile Load Dump);     # libyaml-based (fast)
my $config = LoadFile('config.yml');
DumpFile('out.yml', $config);
# Also: YAML::PP (pure Perl, spec-compliant), YAML::Tiny (minimal subset)

40.3 CSV

Never parse CSV with split /,/: quoted fields, embedded commas, and newlines break it.

use Text::CSV_XS;                     # or Text::CSV (auto-selects XS)
my $csv = Text::CSV_XS->new({ binary => 1, auto_diag => 1 });
open my $fh, '<:encoding(UTF-8)', 'data.csv' or die $!;
my $header = $csv->getline($fh);
$csv->column_names(@$header);
while (my $row = $csv->getline_hr($fh)) {
    say "$row->{name}: $row->{email}";
}
close $fh;

open my $out, '>:encoding(UTF-8)', 'out.csv' or die $!;
$csv->say($out, ['name', 'note']);
$csv->say($out, ['Ana', 'Says "hi", then leaves']);   # quoting handled correctly
close $out;

my $aoh = Text::CSV_XS::csv(in => 'data.csv', headers => 'auto');   # one-call API

40.4 XML and HTML

use XML::LibXML;
my $dom = XML::LibXML->load_xml(location => 'books.xml');
for my $book ($dom->findnodes('//book[price > 20]')) {
    say $book->findvalue('./title'), ': ', $book->findvalue('./price');
}
my $doc = XML::LibXML::Document->new('1.0', 'UTF-8');
my $root = $doc->createElement('catalog'); $doc->setDocumentElement($root);
$root->appendTextChild('item', 'Perl book');
print $doc->toString(1);
# Also: XML::Twig (huge files, streaming), XML::Simple (discouraged), XML::Compile (schemas/SOAP)
# HTML: Mojo::DOM (CSS selectors), HTML::TreeBuilder::XPath, Web::Query

40.5 Other Formats

Excel: Spreadsheet::ParseXLSX, Spreadsheet::Read, Excel::Writer::XLSX. INI: Config::Tiny, Config::IniFiles. TOML: TOML::Tiny. Binary: pack/unpack, Data::MessagePack, Sereal (fast Perl serialization), Storable. PDF: PDF::API2, PDF::Builder. Archives: Archive::Zip, Archive::Tar (core), IO::Compress::Gzip (core).