++ed by:
RRWO HANENKAMP BESSARABV MARCEL DCPETROV

54 PAUSE users
36 non-PAUSE users.

Breno G. de Oliveira

NAME

Data::Printer - colored pretty-print of Perl data structures and objects

SYNOPSIS

  use Data::Printer;   # or just "use DDP" for short

  my @array = qw(a b);
  $array[3] = 'c';
  
  p @array;  # no need to pass references!

Code above will show this (with colored output):

   [
       [0] "a",
       [1] "b",
       [2] undef,
       [3] "c",
   ]

You can also inspect Objects:

    my $obj = SomeClass->new;

    p($obj);

Which might give you something like:

  \ SomeClass  {
      Parents       Moose::Object
      Linear @ISA   SomeClass, Moose::Object
      public methods (3) : bar, foo, meta
      private methods (0)
      internals: {
         _something => 42,
      }
  }
 

If for some reason you want to mangle with the output string instead of printing it to STDERR, you can simply ask for a return value:

  # move to a string
  my $string = p(@some_array);

  # output to STDOUT instead of STDERR
  print p(%some_hash);

  # or even render as HTML
  use HTML::FromANSI;
  ansi2html( p($object) );

Finally, you can set all options during initialization, including coloring, identation and filters!

  use Data::Printer {
      color => {
         'regex' => 'blue',
         'hash'  => 'yellow',
      },
      filters => {
         'DateTime' => sub { $_[0]->ymd },
         'SCALAR'   => sub { "oh noes, I found a scalar! $_[0]" },
      },
  };

You can ommit the first {} block and just initialize it with a regular hash, if it makes things easier to read:

  use Data::Printer  deparse => 1, sort_keys => 0;

And if you like your setup better than the defaults, just put them in a '.dataprinter' file in your home dir and don't repeat yourself ever again :)

RATIONALE

Data::Dumper is a fantastic tool, meant to stringify data structures in a way they are suitable for being eval'ed back in.

The thing is, a lot of people keep using it (and similar ones, like Data::Dump) to print data structures and objects on screen for inspection and debugging, and while you can use those modules for that, it doesn't mean mean you should.

This is where Data::Printer comes in. It is meant to do one thing and one thing only:

display Perl variables and objects on screen, properly formatted (to be inspected by a human)

If you want to serialize/store/restore Perl data structures, this module will NOT help you. Try Storable, Data::Dumper, JSON, or whatever. CPAN is full of such solutions!

COLORS

Below are all the available colorizations and their default values. Note that both spellings ('color' and 'colour') will work.

   use Data::Printer {
     color => {
        array       => 'bright_white',  # array index numbers
        number      => 'bright_blue',   # numbers
        string      => 'bright_yellow', # strings
        class       => 'bright_green',  # class names
        undef       => 'bright_red',    # the 'undef' value
        hash        => 'magenta',       # hash keys
        regex       => 'yellow',        # regular expressions
        code        => 'green',         # code references
        glob        => 'bright_cyan',   # globs (usually file handles)
        repeated    => 'white on_red',  # references to seen values
        caller_info => 'bright_cyan' # details on what's being printed
     },
   };

Don't fancy colors? Disable them with:

  use Data::Printer colored => 0;

Remember to put your preferred settings in the .dataprinter file so you never have to type them at all!

ALIASING

Data::Printer provides the nice, short, p() function to dump your data structures and objects. In case you rather use a more explicit name, already have a p() function (why?) in your code and want to avoid clashing, or are just used to other function names for that purpose, you can easily rename it:

  use Data::Printer alias => 'Dumper';

  Dumper( %foo );

CUSTOMIZATION

I tried to provide sane defaults for Data::Printer, so you'll never have to worry about anything other than typing "p( $var )" in your code. That said, and besides coloring and filtering, there are several other customization options available, as shown below (with default values):

  use Data::Printer {
      name           => 'var',   # name to display on cyclic references
      indent         => 4,       # how many spaces in each indent
      hash_separator => '   ',   # what separates keys from values
      index          => 1,       # display array indices
      multiline      => 1,       # display in multiple lines (see note below)
      max_depth      => 0,       # how deep to traverse the data (0 for all)
      sort_keys      => 1,       # sort hash keys
      deparse        => 0,       # use B::Deparse to expand subrefs
      show_tied      => 1,       # expose tied() variables
      caller_info    => 0,       # include information on what's being printed
      use_prototypes => 1,       # allow p(%foo), but prevent anonymous data

      class_method   => '_data_printer', # make classes aware of Data::Printer
                                         # and able to dump themselves.

      class => {
          internals => 1,        # show internal data structures of classes

          inherited => 'none',   # show inherited methods,
                                 # can also be 'all', 'private', or 'public'.

          expand    => 1,        # how deep to traverse the object (in case
                                 # it contains other objects). Defaults to
                                 # 1, meaning expand only itself. Can be any
                                 # number, 0 for no class expansion, and 'all'
                                 # to expand everything.

          sort_methods => 1      # sort public and private methods
      },
  };

Note: setting multiline to 0 will also set index and indent to 0.

FILTERS

Data::Printer offers you the ability to use filters to override any kind of data display. The filters are placed on a hash, where keys are the types - or class names - and values are anonymous subs that receive two arguments: the item itself as first parameter, and the properties hashref (in case your filter wants to read from it). This lets you quickly override the way Data::Printer handles and displays data types and, in particular, objects.

  use Data::Printer filters => {
            'DateTime'      => sub { $_[0]->ymd },
            'HTTP::Request' => sub { $_[0]->uri },
  };

Perl types are named as ref calls them: SCALAR, ARRAY, HASH, REF, CODE, Regexp and GLOB. As for objects, just use the class' name, as shown above.

As of version 0.13, you may also use the '-class' filter, which will be called for all non-perl types (objects).

Your filters are supposed to return a defined value (usually, the string you want to print). If you don't, Data::Printer will let the next filter of that same type have a go, or just fallback to the defaults. You can also use an array reference to pass more than one filter for the same type or class.

Note: If you plan on calling p() from within an inline filter, please make sure you are passing only REFERENCES as arguments. See "CAVEATS" below.

You may also like to specify standalone filter modules. Please see Data::Printer::Filter for further information on a more powerful filter interface for Data::Printer, including useful filters that are shipped as part of this distribution.

MAKING YOUR CLASSES DDP-AWARE (WITHOUT ADDING ANY DEPS)

Whenever printing the contents of a class, Data::Printer first checks to see if that class implements a sub called '_data_printer' (or whatever you set the "class_method" option to in your settings, see "CUSTOMIZATION" below).

If a sub with that exact name is available in the target object, Data::Printer will use it to get the string to print instead of making a regular class dump.

This means you could have the following in one of your classes:

  sub _data_printer {
      my ($self, $properties) = @_;
      return 'Hey, no peeking! But foo contains ' . $self->foo;
  }

Notice you don't have to depend on Data::Printer at all, just write your sub and it will use that to pretty-print your objects.

If you want to use colors and filter helpers, and still not add Data::Printer to your dependencies, remember you can import them during runtime:

  sub _data_printer {
      require Data::Printer::Filter;
      Data::Printer::Filter->import;

      # now we have 'indent', outdent', 'linebreak', 'p' and 'colored'
      my ($self, $properties) = @_;
      ...
  }

Having a filter for that particular class will of course override this setting.

CONFIGURATION FILE (RUN CONTROL)

Data::Printer tries to let you easily customize as much as possible regarding the visualization of your data structures and objects. But we don't want you to keep repeating yourself every time you want to use it!

To avoid this, you can simply create a file called .dataprinter in your home directory (usually /home/username in Linux), and put your configuration hash reference in there.

This way, instead of doing something like:

   use Data::Printer {
     colour => {
        array => 'bright_blue',
     },
     filters => {
         'Catalyst::Request' => sub {
             my $req = shift;
             return "Cookies: " . p($req->cookies)
         },
     },
   };

You can create a .dataprinter file like this:

   {
     colour => {
        array => 'bright_blue',
     },
     filters => {
         'Catalyst::Request' => sub {
             my $req = shift;
             return "Cookies: " . p($req->cookies)
         },
     },
   };

and from then on all you have to do while debugging scripts is:

  use Data::Printer;

and it will load your custom settings every time :)

THE "DDP" PACKAGE ALIAS

You're likely to add/remove Data::Printer from source code being developed and debugged all the time, and typing it might feel too long. Because of this the 'DDP' package is provided as a shorter alias to Data::Printer:

   use DDP;
   p %some_var;

CALLER INFORMATION

If you set caller_info to a true value, Data::Printer will prepend every call with an informational message. For example:

  use Data::Printer caller_info => 1;

  my $var = 42;
  p $var;

will output something like:

  Printing in line 4 of myapp.pl:
  42

The default message is 'Printing in line __LINE__ of __FILENAME__:'. The special strings __LINE__, __FILENAME__ and __PACKAGE__ will be interpolated into their according value so you can customize them at will:

  use Data::Printer
    caller_info => 1,
    caller_message => "Okay, __PACKAGE__, let's dance!"
    color => {
        caller_info => 'bright_red',
    };

As shown above, you may also set a color for "caller_info" in your color hash. Default is cyan.

EXPERIMENTAL FEATURES

The following are volatile parts of the API which are subject to change at any given version. Use them at your own risk.

Local Configuration (experimental!)

You can override global configurations by writing them as the second parameter for p(). For example:

  p( %var, color => { hash => 'green' } );

Filter classes

As of Data::Printer 0.11, you can create complex filters as a separate module. Those can even be uploaded to CPAN and used by other people! See Data::Printer::Filter for further information.

CAVEATS

You can't pass more than one variable at a time.

   p($foo, $bar); # wrong
   p($foo);       # right
   p($bar);       # right

The default mode is to use prototypes, in which you are supposed to pass variables, not anonymous structures:

   p( { foo => 'bar' } ); # wrong

   p %somehash;        # right
   p $hash_ref;        # also right

To pass anonymous structures, set "use_prototypes" option to 0. But remember you'll have to pass your variables as references:

   use Data::Printer use_prototypes => 0;

   p( { foo => 'bar' } ); # was wrong, now is right.

   p( %foo  ); # was right, but fails without prototypes
   p( \%foo ); # do this instead

If you are using inline filters, and calling p() (or whatever name you aliased it to) from inside those filters, you must pass the arguments to p() as a reference:

  use Data::Printer {
      filters => {
          ARRAY => sub {
              my $listref = shift;
              my $string = '';
              foreach my $item (@$listref) {
                  $string .= p( \$item );      # p( $item ) will not work!
              }
              return $string;
          },
      },
  };

This happens because your filter function is compiled before Data::Printer itself loads, so the filter does not see the function prototype. As a way to avoid unpleasant surprises, if you forget to pass a reference, Data::Printer will generate an exception for you with the following message:

    'If you call p() inside a filter, please pass arguments as references'

Another way to avoid this is to use the much more complete Data::Printer::Filter interface for standalone filters.

EXTRA TIPS

Adding p() to all your loaded modules

(contributed by Árpád Szász)

For even faster debugging you can automatically add Data::Printer's p() function to every loaded module using this in your main program:

    BEGIN {
        {
            use Data::Printer;
            no strict 'refs';
            foreach my $package ( keys %main:: ) {
                my $alias = 'p';
                *{ $package . $alias } = \&Data::Printer::p;
            }
        }
    }

WARNING This will override all locally defined subroutines/methods that are named p, if they exist, in every loaded module, so be sure to change $alias to something custom.

Circumventing prototypes

The p() function uses prototypes by default, allowing you to say:

  p %var;

instead of always having to pass references, like:

  p \%var;

There are cases, however, where you may want to pass anonymous structures, like:

  p { foo => $bar };   # this blows up, don't use

and because of prototypes, you can't. If this is your case, just set "use_prototypes" option to 0. Note, with this option, you will have to pass your variables as references:

  use Data::Printer use_prototypes => 0;

   p { foo => 'bar' }; # doesn't blow up anymore, works just fine.

   p %var;  # but now this blows up...
   p \%var; # ...so do this instead

In versions prior to 0.17, you could use &p() instead of p() to circumvent prototypes and pass elements (including anonymous variables) as REFERENCES. This notation, however, requires enclosing parentheses:

  &p( { foo => $bar } );        # this is ok, use at will
  &p( \"DEBUGGING THIS BIT" );  # this works too

Or you could just create a very simple wrapper function:

  sub pp { p @_ };

And use it just as you use p().

BUGS

If you find any, please file a bug report.

SEE ALSO

Data::Dumper

Data::Dump

Data::Dumper::Concise

Data::Dump::Streamer

Data::PrettyPrintObjects

Data::TreeDumper

AUTHOR

Breno G. de Oliveira <garu at cpan.org>

CONTRIBUTORS

Many thanks to everyone that helped design and develop this module with patches, bug reports, wishlists, comments and tests. They are (alphabetically):

  • Árpád Szász

  • brian d foy

  • Chris Prather (perigrin)

  • Damien Krotkine (dams)

  • Dotan Dimet

  • Eden Cardim (edenc)

  • Fernando Corrêa (SmokeMachine)

  • Kartik Thakore (kthakore)

  • Kip Hampton (ubu)

  • Paul Evans (LeoNerd)

  • Sergey Aleynikov (randir)

  • sugyan

  • Tatsuhiko Miyagawa (miyagawa)

  • Torsten Raudssus (Getty)

If I missed your name, please drop me a line!

LICENSE AND COPYRIGHT

Copyright 2011 Breno G. de Oliveira <garu at cpan.org>. All rights reserved.

This module is free software; you can redistribute it and/or modify it under the same terms as Perl itself. See perlartistic.

DISCLAIMER OF WARRANTY

BECAUSE THIS SOFTWARE IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE SOFTWARE, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE SOFTWARE "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE SOFTWARE IS WITH YOU. SHOULD THE SOFTWARE PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR, OR CORRECTION.

IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE SOFTWARE AS PERMITTED BY THE ABOVE LICENCE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE SOFTWARE (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE SOFTWARE TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.

1 POD Error

The following errors were encountered while parsing the POD:

Around line 1074:

Non-ASCII character seen before =encoding in 'Árpád'. Assuming UTF-8