Printing Data Structures

Problem

You want to print out a data structure.

Solution

If the output’s legibility and layout are important, write your own custom printing routine.

If you are in the Perl debugger, use the x command:

DB<1> $reference = [ { "foo" => "bar" }, 3, sub { print "hello, world\n" } ];
DB<2> x $reference

                    0  ARRAY(0x1d033c)
               
                      0  HASH(0x7b390)
               
                         'foo' = 'bar'>
               
                      1  3
               
                      2  CODE(0x21e3e4)
               
                         - & in ???>

From within your own programs, use the Dumper function from the CPAN module Data::Dumper:

use Data::Dumper;
print Dumper($reference);

Discussion

Sometimes you’ll want to make a dedicated function for your data structure that delivers a particular output format, but often this is overkill. If you’re running under the Perl debugger, the x and X commands provide nice pretty-printing. The x command is more useful because it works on both global and lexical variables, whereas X only works on globals. Pass x a reference to the data structure you want to print.

D<1> x \@INC

                    0  ARRAY(0x807d0a8)
               
                       0  '/home/tchrist/perllib' 
               
                       1  '/usr/lib/perl5/i686-linux/5.00403'
               
                       2  '/usr/lib/perl5' 
               
                       3  '/usr/lib/perl5/site_perl/i686-linux' 
               
                       4  '/usr/lib/perl5/site_perl' 
               
                       5  '.'
               

These commands use the dumpvar.pl library. Here’s an example:

{ package main; require "dumpvar.pl" } 
*dumpvar = \&main::dumpvar if __PACKAGE_ _ ne 'main';
dumpvar("main", "INC");             # show both @INC and %INC

The dumpvar.pl library isn’t a module, but we wish it were—so we cajole it into exporting its dumpvar function anyway. The first two ...

Get Perl Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.