Pretty-Printing
In
building complicated data structures, it is always nice to have a
pretty-printer handy for debugging. There are at least two options
for pretty-printing data structures. The first is the
Perl debugger itself. It uses a
function called dumpValue in a file called
dumpvar.pl, which can be found in the standard
library directory. We can help ourselves to it, with the caveat that
it is an unadvertised function and could change someday. To
pretty-print this structure, for example:
@sample = (11.233,{3 => 4, "hello" => [6,7]});we write the following:
require 'dumpvar.pl'; dumpValue(\@sample); # always pass by reference
This prints something like this:
0 11.233
1 HASH(0xb75dc0)
3 => 4
'hello' => ARRAY(0xc70858)
0 6
1 7We will cover the require statement in Chapter 6. Meanwhile, just think of it as a fancy
#include (which doesn’t load the file if it
is already loaded).
The Data::Dumper module available from CPAN is another viable alternative for pretty-printing. Chapter 10, covers this module in some detail, so we will not say any more about it here. Both modules detect circular references and handle subroutine and glob references.
It is fun and instructive to write a pretty-printer ourselves. Example 2.5 illustrates a simple effort, which accounts for circular references but doesn’t follow typeglobs or subroutine references. This example is used as follows:
pretty_print(@sample); # Doesn't need a referenceThis prints
11.233 { # HASH(0xb78b00) : 3 => 4 : hello => : : [ # ...Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access