Inspect Perl values prettily with Data::Printer

thibaultduponchelle

Tib

Posted on March 4, 2021

Inspect Perl values prettily with Data::Printer

A word about complex structures and debugging

In Perl (as in majority of other programming languages), you can construct complex data structures. By complex, I mean mixed hash and arrays or nested (hash of hashes, array of hashes etc...).

Then it typically requires time and effort to do "printf debugging" on these complex structures so that's the reason why data dumpers exist!

So let's go with the code!

First fill a variable to dump

I propose this small snippet to create and fill an array with some content:

#!/usr/bin/env perl

my @array = ();
push @array, "apple";
push @array, "banana";
push @array, "strawberry";
push @array, { name => "tib", color => "blue" };
push @array, { name => "bob", color => "red" };
Enter fullscreen mode Exit fullscreen mode

An array with items where some of them are hashes (refs).

Data::Dumper

First I will dump with the classic Data::Dumper πŸ˜ƒ

use Data::Dumper;
print Dumper(@array);
Enter fullscreen mode Exit fullscreen mode

The output is already not bad (hash is indented):
Data::Dumper

To improve output, we can tweak a bit the behavior of Data::Dumper but if you want my opinion there is a better option...

Data::Printer

First, install Data::Printer with a CPAN client cpanm Data::Printer.

Data::Printer is not in the core (Data::Dumper is) but has no "non-core" dependencies! πŸ’ƒ

use DDP;
p @array;
Enter fullscreen mode Exit fullscreen mode

And tadaa! A nicely formatted and colored data dump πŸ‘
Data::Printer

πŸ’– πŸ’ͺ πŸ™… 🚩
thibaultduponchelle
Tib

Posted on March 4, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related