Class custom dumping for Data::Dump

I'm using DateTime objects a lot these days: anytime I get some date/time data from outside of Perl, the first thing I do is convert them to DateTime object, to avoid calculation/formatting hassle ahead.

However, the dumps are not pretty.

% perl -MDateTime -MData::Dump -e'dd [DateTime->now]'
[
  bless({
    formatter       => undef,                                         
    local_c         => {
                         day => 21,
                         day_of_quarter => 51,
                         day_of_week => 5,
                         day_of_year => 141,
                         hour => 8,
                         minute => 55,
                         month => 5,
                         quarter => 2,
                         second => 36,
                         year => 2010,
                       },
    local_rd_days   => 733913,
    local_rd_secs   => 32136,
    locale          => bless({
                         "default_date_format_length" => "medium",
                         "default_time_format_length" => "medium",
                         en_complete_name => "English United States",
                         en_language => "English",
                         en_territory => "United States",
                         id => "en_US",
                         native_complete_name => "English United States",
                         native_language => "English",
                         native_territory => "United States",
                       }, "DateTime::Locale::en_US"),
    offset_modifier => 0,
    rd_nanosecs     => 0,
    tz              => bless({ name => "UTC" }, "DateTime::TimeZone::UTC"),
    utc_rd_days     => 733913,
    utc_rd_secs     => 32136,
    utc_year        => 2011,
  }, "DateTime"),
]
It gets worse when you have some records each with DateTime object in it. That's why I added a couple of mechanisms to allow us to custom a class' dump.
$ perl -Ilib -MDateTime -MData::Dump -e'$Data::Dump::CUSTOM_CLASS_DUMPERS{"DateTime"} = sub { "$_[0]" }; dd [DateTime->now]'
[2010-05-21T08:57:45]

or:

$ perl -Ilib -MDateTime -MData::Dump -e'package DateTime; sub dump { "$_[0]" }; package main; dd [DateTime->now]'
[2010-05-21T08:58:09]

I know some other dumper in CPAN probably has this ability, but I like Data::Dump's output.

If you want to take a look at a couple of small patches to Data::Dump: http://github.com/sharyanto/data-dump

2 Comments

This is extremely cool. I want it for Data::Dumper too. :)

Data-Dump-1.16 now supports filter callbacks that can be used for these kind of tweaks.

Leave a comment

About Steven Haryanto

user-pic A programmer (mostly Perl 5 nowadays). My CPAN ID: SHARYANTO. I'm sedusedan on perlmonks. My twitter is stevenharyanto (but I don't tweet much). Follow me on github: sharyanto.