Data::Dump

2023-12-18 perl dump Data::Dump debugging

Working with perl programs, one of the most useful features for debugging is ability to dump the data structures recursively to see its contents. My favorite module for this task is built-in Data::Dump.

Usage is pretty simple. The module provides two basic methods, dd and pp. Former prints the output to the standard output, while latter returns the formatted output as a string.

A simple example:

use Data::Dump qw(dd pp);

my $simple = {
    a => [1..10],
    b => [2..15],
    c => [qw(e f g)],
};

dd $simple;

Gets:

{ a => [1 .. 10], b => [2 .. 15], c => ["e", "f", "g"] }

If the structure is larger, it also adds nice formatting:

my $complex = {
    name    => 'Roman',
    address => '123 Street, New Hampshire',
    phone   => '+111 123 123456',
};

dd $complex;

Prints

{
  address => "123 Street, New Hampshire",
  name    => "Roman",
  phone   => "+111 123 123456",
}

The pp variant is useful whenever we want to do something extra with the text, say format it into an email, write it to the log or anything.

One nice property is that the generated output, when evaluated should produce same structure as the input. This has of course some limitations (like embedded subroutines), but generally can work quite well.