home | O'Reilly's CD bookshelfs | FreeBSD | Linux | Cisco | Cisco Exam  

Perl CookbookPerl CookbookSearch this book

11.11. Printing Data Structures

11.11.3. 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 works only on globals. Pass x a reference to the data structure you want to print.

DB<3> 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  '.'

The standard Dumpvalue module provides the Debugger's output formatting using an object-oriented interface. Here's an example:

use Dumpvalue;
Dumpvalue->new->dumpvars("main", "INC");

@INC = (
   0  '/usr/local/lib/perl5/5.8.1/OpenBSD.i386-openbsd'
   1  '/usr/local/lib/perl5/5.8.1'
   2  '/usr/local/lib/perl5/site_perl/5.8.1/OpenBSD.i386-openbsd'
   3  '/usr/local/lib/perl5/site_perl/5.8.1'
   4  '/usr/local/lib/perl5/site_perl/5.8.0/OpenBSD.i386-openbsd'
   5  '/usr/local/lib/perl5/site_perl/5.8.0'
   6  '/usr/local/lib/perl5/site_perl'
   7  '.'
%INC = (
   'Dumpvalue.pm' = '/usr/local/lib/perl5/5.8.1/Dumpvalue.pm'>
   'strict.pm' = '/usr/local/lib/perl5/5.8.1/strict.pm'>

which is like using the V main INC command in the Debugger. All the output formatting options from the Debugger are available from Dumpvalue. Just pass Dumpvalue->new option pairs:

$dobj = Dumpvalue->new(option1 => value1, option2 => value2);

Options available as of v5.8.1 include arrayDepth, hashDepth, compactDump, veryCompact, globPrint, dumpDBFiles, dumpPackages, dumpReused, tick, quoteHighBit, printUndef, usageOnly, unctrl, subdump, bareStringify, quoteHighBit, and stopDbSignal.

The Data::Dumper module, also included in the standard Perl distribution, has a different approach. It provides a Dumper function that takes a list of references and returns a string with a printable (and eval able) form of those references.

use Data::Dumper; print Dumper(\@INC); 
$VAR1 = [
'/usr/local/lib/perl5/site_perl', '.'

Data::Dumper supports a variety of output formats. Check its documentation for details. Particularly useful is the option to decompile Perl code:

use Data::Dumper;
$Data::Dumper::Deparse = 1;
$a = sub { print "hello, world\n" };
print Dumper($a);
$VAR1 = sub {
                  print 'hello, world';

Library Navigation Links

Copyright © 2003 O'Reilly & Associates. All rights reserved.