YAML::XS(3)

✨ YAML::XS πŸ’–

okay bestie, gather round, because this is the Perl YAML serialization glow-up you've been waiting for β€” it's YAML::XS, and it lives in the User Contributed Perl Documentation section, manual page YAML::XS(3). πŸŽ€

🌸 NAME 🌸

YAML::XS β€” Perl YAML Serialization using XS and libyaml. that's it, that's the whole vibe. πŸ¦‹


✨ SYNOPSIS ✨

use YAML::XS;

# Classic functional interface
my $yaml = Dump [ 1..4 ];
my $array = Load $yaml;

# EXPERIMENTAL: Object Oriented interface for YAML 1.2
# Incompatible to functional interface!
my $xs = YAML::XS->new;
my $yaml = $xs->dump([ 1..4 ]);
my $array = $xs->load($yaml);

πŸ’… DESCRIPTION πŸ’…

so Kirill Simonov's libyaml? arguably the best YAML implementation, no cap. it's a C library written precisely to the YAML 1.1 specification. it was originally bound to Python, and then later it got bound to Ruby. main character behavior fr. πŸ‘‘

this module is a Perl XS binding to libyaml, and it hands Perl the best YAML support to date. periodt. πŸ’–

it exports the functions Dump, Load, DumpFile and LoadFile. these are intended to work exactly like YAML.pm's corresponding functions. but heads up bestie: only Load and Dump are exported by default. the other two you gotta ask for. πŸ™ˆ


🧚 CONFIGURATION 🧚

the object oriented interface is described below: see "OBJECT ORIENTED INTERFACE".

  • $YAML::XS::LoadBlessed (since v0.69)

Default: false.

⚠️ the default was changed in version 0.81. so if you're on old code, vibe check your version.

when it's set to false, it will not bless data into objects β€” and ngl that can be a security problem when you're loading YAML from an untrusted source. it will silently ignore the tag and just load the data unblessed. it's giving "nothing to see here".

in PyYAML, this is called SafeLoad.

if you set it to true, it will load the following YAML as objects:

---
local: !Foo::Bar [a]
perl: !!perl/hash:Foo::Bar { a: 1 }
regex: !!perl/regexp:Foo::Bar pattern

you can create any kind of object with YAML. the creation itself is not the critical part. but if the class has a DESTROY method, it will be called once the object is deleted. there's an example with File::Temp removing files over at <https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=862373>. so like... be careful, bestie. 😭

  • $YAML::XS::ForbidDuplicateKeys (since 0.84)

Default: false

when set to true, Load will die when it encounters a duplicate key in a hash, like:

key: value
key: another value

this is lowkey useful for bigger YAML documents where a dup is not that obvious, and honestly it's recommended to set it to true. that's also what a YAML loader should do by default according to the YAML specification. so yeah. πŸ‘‘

  • $YAML::XS::UseCode
  • $YAML::XS::DumpCode
  • $YAML::XS::LoadCode

if enabled, it supports deparsing and evaling of code blocks. πŸ”₯

note that support for loading code was added in version 0.75, even though $LoadCode was already documented in earlier versions. so it was documented before it existed. iconic behavior honestly.

  • $YAML::XS::QuoteNumericStrings

when true (which is the default), strings that look like numbers but have not been numified will be quoted when dumping. πŸ’…

this ensures that things like leading zeros and other formatting are preserved. so 007 stays 007 and doesn't turn into 7. we love to see it.

  • $YAML::XS::Boolean (since v0.67)

Default: undef

since YAML::XS 0.89: when used with perl 5.36 or later, builtin booleans will work out of the box. they will be created by Load and recognized by Dump automatically (since YAML::XS 0.89). πŸŽ€

say Dump({ truth => builtin::true });
# truth: true

since YAML::XS v0.902: loaded booleans are not set to readonly anymore. slay.

for older perl versions you can use the following configuration to serialize data as YAML booleans:

when set to JSON::PP or boolean, the plain (unquoted) strings true and false will be loaded as JSON::PP::Boolean or boolean.pm objects. those objects will be dumped again as plain true or false.

it will try to load [JSON::PP] or [boolean] and die if it can't be loaded. 😭

with that it's possible to add new "real" booleans to a data structure:

local $YAML::XS::Boolean = "JSON::PP"; # or "boolean"
my $data = Load("booltrue: true");
$data->{boolfalse} = JSON::PP::false;
my $yaml = Dump($data);
# boolfalse: false
# booltrue: true

it also lets booleans survive when loading YAML via YAML::XS and encode it in JSON via one of the various JSON encoders, which mostly support JSON::PP booleans. πŸ¦‹

please note that JSON::PP::Boolean and boolean.pm behave a bit differently. ideally you should only use them in boolean context. don't get cute with them.

if not set, booleans are loaded as special perl variables PL_sv_yes and PL_sv_no, which have the disadvantage that they are readonly, and you can't add those to an existing data structure with pure perl. that's the tradeoff, bestie. πŸ’€

if you simply need to load "perl booleans" that are true or false in boolean context, you will be fine with the default setting. πŸ‘

  • $YAML::XS::Indent (since v0.76)

Default is 2.

sets the number of spaces for indentation for Dump.


🌈 USING YAML::XS WITH UNICODE 🌈

handling unicode properly in Perl can be a pain. YAML::XS only deals with streams of utf8 octets. just remember this, bestie:

$perl = Load($utf8_octets);
$utf8_octets = Dump($perl);

there are many, many places where things can go wrong with unicode. if you are having problems, use Devel::Peek on all the possible data points. that's the vibe check you need. πŸ”


πŸ‘‘ OBJECT ORIENTED INTERFACE πŸ‘‘

since version v0.904.0, EXPERIMENTAL.

⚠️ NOTE: this is incompatible with the functional interface and will treat YAML values in a different way. so like, don't mix them and expect them to be besties. they are not besties.

this has two MAJOR differences to the old functional interface:

Object with options

this provides an interface where you create a YAML::XS object with options (instead of the old interface with global variables). glow-up fr. ✨

YAML 1.2 Core Schema

it implements the YAML 1.2 Core Schema.

(note that the functional interface does not implement YAML 1.1, when it comes to loading numbers, booleans, null etc. it implements its own set of rules.)

here is an (incomplete!) example of values that are treated differently than with the functional interface. YAML values that match a certain pattern are not loaded as strings, but as other types:

# Functional interface: special values (not compatible to other YAML modules)
- [true, false]                             # booleans
- [null, ~]                                 # undef
- [inf, INF, iNf, iNF, InF, INf, -inf, ...] # Inf
- [100_000]                                 # 100000
- # anything that looks_like_number()       # number

# OOP YAML 1.2 special values
- [true, True, TRUE, false, False, FALSE]   # booleans
- [null, Null, NULL, ~]                     # undef
- [.inf, .Inf, .INF, -.inf, -.Inf, -.INF]   # Inf
- [.nan, .NAN, .NaN]                        # nan
- [42, 0x10, 0o10]                          # dec 42, hex 16, oct 8

for more subtle differences regarding numbers checkout the comprehensive data here:

YAML 1.1 / 1.2 definitions: <https://perlpunk.github.io/yaml-test-schema/schemas.html> Test data: <https://perlpunk.github.io/yaml-test-schema/data.html>

this way the OOP interface is compatible to YAML::PP and YAML processors in other languages supporting YAML 1.2. cross-language friendship, we love it. 🫢

  • "load" will return the first document in scalar context β€” the functional interface returns the last.
  • numbers don't have string flags.
  • booleans currently are only preserved for the new builtin booleans β€” adding a JSON::PP boolean option for older perls is planned.
  • references, objects, globs, regexes and coderefs cannot be loaded or dumped β€” this is planned.

Usage

use YAML::XS ();
my $xs = YAML::XS->new;
my $yaml = "foo: bar";

# Load single (first) document:
my $data = $xs->load($yaml);
$yaml = $xs->dump($data);

# Or to load all documents:
my @data = $xs->load($yaml);
$yaml = $xs->dump(@data);

METHODS

new

use YAML::XS;
my $xs = YAML::XS->new(
    # load options
    # require_footer => 0,

    # dump options
    # indent => 2,
    # header => 1,
    # footer => 0,
    # width => 80,
    # anchor_prefix => '',
    # cyclic_refs => 0,

    # load and dump options
    # utf8 => 0,
);

Options:

  • indent β€” Default: 2. sets the number of spaces for indentation for dumping. πŸ’…
  • utf8 β€” Default: false. when false, the loader will accept unencoded character strings, and the dumper returns unencoded character strings. when true, the loader accepts a UTF-8 encoded string of bytes, and the dumper returns a UTF-8 encoded string of bytes. this typically makes sense when you read from / write to a file directly. 🌸
  • header β€” Default: 1. writes a "---" before every document. ✨
  • footer β€” Default: 0. writes a "..." at the end of every document.
  • width β€” set the maximum number of colums for dumping. if a value has too many characters, it will be split into multiple lines.
  • require_footer β€” Default: 0. can be useful in a use case where you want to make sure you received the complete document from the sender. πŸ“¨
  • anchor_prefix β€” Default: ''. if set to a string like "ANCHOR", anchors and aliases will be prefixed with this instead of just being numbers:
# my $xs = YAML::XS->new( anchor_prefix => 'ANCHOR' );
# my $hash = { some => "mapping" };
# say $xs->dump([$hash, $hash]);
- &ANCHOR1
  some: mapping
- *ANCHOR1
  • cyclic_refs β€” since version v0.907. Default: 0. YAML can contain data structures where an alias points to a node containing the current node, creating a cyclic (circular) data structure. if you load untrusted YAML documents, that can lead to memory leaks. 😭 since it's not a very common use case, YAML::XS defaults to not allowing it. it will just behave as if the anchor was never created in this case. you an set it to 1 to allow it.

load

my $yaml = <<'EOM';
---
- 23
---
some: mapping
EOM
my $array = $xs->load($yaml);
# [23]
my @documents = $xs->load($yaml);
# (
#   [23],
#   { some => "mapping" }
# )

in scalar context, if the YAML string contains more than one document, it will return the first document. πŸ‘‘

dump

$yaml = $xs->dump($data);
$yaml = $xs->dump($data1, $data2, $data3);
$yaml = $xs->dump(@data);

πŸ’… LIBYAML πŸ’…

okay so you can actually clock which libyaml version this module was built with β€” since v.079, bestie, so if you're on anything older, sorry babe, no dice πŸŽ€

my $libyaml_version = YAML::XS::LibYAML::libyaml_version();

literally just call that and boom, you got your answer. no cap. πŸ¦‹


✨ SEE ALSO ✨

go read these too, they're all in the same friend group 🫢

  • YAML.pm
  • YAML::Syck
  • YAML::Tiny
  • YAML::PP
  • YAML::PP::LibYAML

πŸ‘‘ AUTHORS πŸ‘‘

the icons who made this whole thing happen:

  • Ingy dΓΆt Net ingy@ingy.net <mailto:ingy@ingy.net>
  • Tina MΓΌller <tinita@cpan.org>

Copyright 2007-2025 - Ingy dΓΆt Net

This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. slay, it's open source bestie 🌈

See <http://www.perl.com/perl/misc/Artistic.html>


that's the whole page, you made it to the end, i'm so proud of you fr fr πŸ₯Ή

this was perl v5.42.2 energy, dated 2026-05-11, filed under YAML::XS(3) β€” mwah, go write some YAML, you absolute legend πŸ‘‘βœ¨

πŸ“¦ where this page comes from