How to convert Perl hash to YAML string?

Question

How to convert Perl hash to YAML string?

Converting a Perl hash to a YAML string is a common task when you want to serialize data in a human-readable format. YAML (YAML Ain't Markup Language) is popular for configuration files, data exchange, and debugging because it is both easy to read and write.

In Perl, the most straightforward way to convert a hash to a YAML string is by using core or widely available modules like YAML::Tiny or YAML. Since YAML::Tiny is a minimal and core-ish dependency, it's a great choice for beginners and simple tasks. The full YAML module offers more features but requires installation from CPAN if not already available.

How to convert a hash to YAML with YAML::Tiny

The YAML::Tiny module serializes Perl data structures (hashes, arrays, scalars) into valid YAML. It returns a YAML string that you can print or save.

  • YAML::Tiny->new() creates a new YAML object
  • write_string() returns a YAML string representation of the data

The resulting YAML will be a string in scalar context, which you can print directly.

Perl code example

use strict;
use warnings;
use YAML::Tiny;

# Sample Perl hash
my %data = (
    name    => "Alice",
    age     => 30,
    skills  => [ 'Perl', 'YAML', 'Serialization' ],
    address => {
        city  => "New York",
        state => "NY",
    },
);

# Create a new YAML::Tiny object
my $yaml = YAML::Tiny->new;

# Convert the hash to a YAML string
# Note: YAML::Tiny expects an arrayref, so wrap \%data in []
my $yaml_string = $yaml->write_string([\%data]);

print $yaml_string;

Explanation of key Perl concepts

  • Sigils: In %data, the percent sign indicates a hash. When passing a hash reference, use \\%data. Wrapping in arrayref [\\%data] is a YAML::Tiny requirement since it serializes an array of documents.
  • Context: The write_string method returns a scalar YAML string. Perl context helps determine how functions return values based on expected usage.
  • TMTOWTDI: ("There's more than one way to do it") - You could also use other YAML libraries like YAML or YAML::XS for different performance or feature needs.

Common pitfalls

  • Remember to pass a reference to your data. Plain hashes or arrays won’t serialize directly.
  • YAML::Tiny only supports basic YAML features, so if you need advanced features (like anchors or complex data), consider YAML::XS.
  • When printing to the console, ensure your output encoding matches your terminal to avoid Unicode issues (usually binmode(STDOUT, ":utf8") in Unicode contexts).

Summary

To convert a Perl hash to a YAML string, use the YAML::Tiny module’s write_string() method with a reference to your hash. This yields a clean, readable YAML string you can output or store. It's an easy way to serialize data for configs, logging, or interoperation.

Verified Code

Executed in a sandbox to capture real output. • v5.34.1 • 20ms

Tip: edit code and use “Run (Browser)”. Server runs always execute the published, verified snippet.
STDOUT
(empty)
STDERR
(empty)

Was this helpful?

Related Questions