How to dump Perl data structure to YAML format?
Question
How to dump Perl data structure to YAML format?
How to Dump Perl Data Structures to YAML Format
Serializing Perl data structures to YAML format is common when you want to store or transmit configuration or data in a human-readable form. YAML (YAML Ain't Markup Language) is a flexible text format often preferred over JSON or XML for its readability.
In Perl, the most popular way to dump data structures as YAML is by using the YAML or YAML::XS modules, which are not part of the core Perl distribution but are widely used and available via CPAN. However, since you requested no external modules, the core Perl does not include native YAML support. You can install YAML modules easily, but for strictly core-only environments, you’d need to serialize manually or use another format like JSON.
Here, I will show you a simple example using YAML::Tiny (which is lightweight and often included) and also a demonstration on how to dump a hash in YAML style manually using Perl core features. Note this manual approach is limited and only intended for very basic structures.
Recommended: Using YAML::Tiny or YAML
If you can use CPAN modules, install YAML::Tiny (or YAML, YAML::XS) as follows:
use YAML::Tiny;
my $data = {
name => 'Alice',
age => 30,
pets => ['dog', 'cat'],
};
my $yaml = YAML::Tiny->new( $data );
print $yaml->write_string;
This prints:
age: 30
name: Alice
pets:
- dog
- cat
Note: You must have YAML::Tiny installed. Run cpan YAML::Tiny or cpanm YAML::Tiny if needed.
Manual Basic YAML Dump with Core Perl Only
If you cannot use any modules, here’s a very minimal example to print a simple hashref in a YAML-like format. This bypasses the complexity of YAML serialization and only supports shallow hashes and arrayrefs.
use strict;
use warnings;
my $data = {
name => 'Alice',
age => 30,
pets => ['dog', 'cat'],
};
sub dump_yaml {
my ($data, $indent) = @_;
$indent //= 0;
my $prefix = ' ' x $indent;
if (ref $data eq 'HASH') {
for my $key (sort keys %$data) {
my $val = $data->{$key};
print $prefix, $key, ":";
if (ref $val eq 'ARRAY') {
print "\n";
for my $item (@$val) {
print $prefix, " - $item\n";
}
} else {
print " $val\n";
}
}
} else {
print $prefix, $data, "\n";
}
}
dump_yaml($data);
This outputs:
age: 30
name: Alice
pets:
- dog
- cat
Explanation of Perl Concepts Used
- References: The complex data is a hash reference (
{ ... }) containing scalars and an array reference. - Context: The printing uses simple scalar context to print values; no advanced overload or stringification.
- TMTOWTDI: Perl’s philosophy “There’s More Than One Way To Do It” means you can manually craft the YAML or use a module.
- Modules: The commonly recommended approach is to use
YAMLmodules as they handle corner cases like quoting strings, nested structures, and special characters.
Common Pitfalls
- Manual serialization limitations: The manual approach does NOT handle nested hashes or complex data.
- Modules required for full YAML spec support: Avoid rolling your own if reliable YAML output is needed.
- Proper quoting: YAML sometimes requires quoting strings with special characters, which modules handle automatically.
- Data types: Perl does not intrinsically preserve data types (e.g., integers vs strings), potentially causing ambiguities unless the serializer manages them.
In Summary
To reliably dump Perl data structures to YAML, use an established CPAN module like YAML::Tiny, YAML, or YAML::XS. For very simple or limited needs without modules, you can write a basic serializer for hashes and arrays, but it won’t cover YAML syntax fully. Perl’s flexible referencing and context make this straightforward with modules.
Verified Code
Executed in a sandbox to capture real output. • v5.34.1 • 19ms
---
age: 30
name: Alice
pets:
- dog
- cat
(empty)