DEV Community

Cover image for Inspect Perl values prettily with Data::Printer
Tib
Tib

Posted on

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

Top comments (1)

Collapse
 
smonff profile image
🌌 Sébastien Feugère ☔ • Edited

No need to say that if complex objects are passed to Data::Printer, they are properly printed, with all their attributes, methods, inheritance tree, etc. Priceless tool that simplify debugging strongly.