4 use vars qw(@EXPORT @EXPORT_OK $VERSION $DEBUG);
8 *import = \&Exporter::import;
10 @EXPORT_OK = qw(dump pp quote);
16 use vars qw(%seen %refcnt @dump @fixup %require $TRY_BASE64);
18 $TRY_BASE64 = 50 unless defined $TRY_BASE64;
20 my %is_perl_keyword = map { $_ => 1 }
21 qw( __FILE__ __LINE__ __PACKAGE__ __DATA__ __END__ AUTOLOAD BEGIN CORE
22 DESTROY END EQ GE GT INIT LE LT NE abs accept alarm and atan2 bind
23 binmode bless caller chdir chmod chomp chop chown chr chroot close
24 closedir cmp connect continue cos crypt dbmclose dbmopen defined
25 delete die do dump each else elsif endgrent endhostent endnetent
26 endprotoent endpwent endservent eof eq eval exec exists exit exp fcntl
27 fileno flock for foreach fork format formline ge getc getgrent
28 getgrgid getgrnam gethostbyaddr gethostbyname gethostent getlogin
29 getnetbyaddr getnetbyname getnetent getpeername getpgrp getppid
30 getpriority getprotobyname getprotobynumber getprotoent getpwent
31 getpwnam getpwuid getservbyname getservbyport getservent getsockname
32 getsockopt glob gmtime goto grep gt hex if index int ioctl join keys
33 kill last lc lcfirst le length link listen local localtime lock log
34 lstat lt m map mkdir msgctl msgget msgrcv msgsnd my ne next no not oct
35 open opendir or ord pack package pipe pop pos print printf prototype
36 push q qq qr quotemeta qw qx rand read readdir readline readlink
37 readpipe recv redo ref rename require reset return reverse rewinddir
38 rindex rmdir s scalar seek seekdir select semctl semget semop send
39 setgrent sethostent setnetent setpgrp setpriority setprotoent setpwent
40 setservent setsockopt shift shmctl shmget shmread shmwrite shutdown
41 sin sleep socket socketpair sort splice split sprintf sqrt srand stat
42 study sub substr symlink syscall sysopen sysread sysseek system
43 syswrite tell telldir tie tied time times tr truncate uc ucfirst umask
44 undef unless unlink unpack unshift untie until use utime values vec
45 wait waitpid wantarray warn while write x xor y);
59 my $val = _dump($v, $name, [], tied($v));
60 push(@dump, [$name, $val]);
67 for (sort keys %require) {
68 $out .= "require $_;\n";
72 # output all those with refcounts first
76 $out .= "my \$$name = $_->[1];\n";
85 my $paren = (@dump != 1);
86 $out .= "(" if $paren;
87 $out .= format_list($paren, undef,
88 map {defined($_->[1]) ? $_->[1] : "\$".$_->[0]}
91 $out .= ")" if $paren;
93 if (%refcnt || %require) {
95 $out =~ s/^/ /gm; # indent
99 #use Data::Dumper; print Dumper(\%refcnt);
100 #use Data::Dumper; print Dumper(\%seen);
102 print STDERR "$out\n" unless defined wantarray;
109 print dump(@_), "\n";
113 my(undef, $file, $line) = caller;
114 $file =~ s,.*[\\/],,;
115 my $out = "$file:$line: " . dump(@_) . "\n";
123 my $rval = $ref ? $_[0] : \$_[0];
126 my($name, $idx, $dont_remember) = @_;
128 my($class, $type, $id);
129 if (overload::StrVal($rval) =~ /^(?:([^=]+)=)?([A-Z]+)\(0x([^\)]+)\)$/) {
134 die "Can't parse " . overload::StrVal($rval);
136 if ($] < 5.008 && $type eq "SCALAR") {
137 $type = "REF" if $ref eq "REF";
139 warn "\$$name(@$idx) $class $type $id ($ref)" if $DEBUG;
141 unless ($dont_remember) {
142 if (my $s = $seen{$id}) {
143 my($sname, $sidx) = @$s;
145 my $sref = fullname($sname, $sidx,
146 ($ref && $type eq "SCALAR"));
147 warn "SEEN: [\$$name(@$idx)] => [\$$sname(@$sidx)] ($ref,$sref)" if $DEBUG;
148 return $sref unless $sname eq $name;
150 push(@fixup, fullname($name,$idx)." = $sref");
151 return "do{my \$fix}" if @$idx && $idx->[-1] eq '$';
154 $seen{$id} = [$name, $idx];
158 if ($type eq "SCALAR" || $type eq "REF" || $type eq "REGEXP") {
160 if ($class && $class eq "Regexp") {
164 if ($v =~ /^\(\?([msix-]+):([\x00-\xFF]*)\)\z/) {
171 my $sep_count = ($v =~ tr/\///);
173 # see if we can find a better one
174 for ('|', ',', ':', '#') {
175 my $c = eval "\$v =~ tr/\Q$_\E//";
176 #print "SEP $_ $c $sep_count\n";
177 if ($c < $sep_count) {
180 last if $sep_count == 0;
184 $v =~ s/\Q$sep\E/\\$sep/g;
186 $out = "qr$sep$v$sep$mod";
190 delete $seen{$id} if $type eq "SCALAR"; # will be seen again shortly
191 my $val = _dump($$rval, $name, [@$idx, "\$"]);
192 $out = $class ? "do{\\(my \$o = $val)}" : "\\$val";
195 if (!defined $$rval) {
198 elsif ($$rval =~ /^-?[1-9]\d{0,9}$/ || $$rval eq "0") {
204 if ($class && !@$idx) {
205 # Top is an object, not a reference to one as perl needs
207 my $obj = fullname($name, $idx);
208 my $cl = quote($class);
209 push(@fixup, "bless \\$obj, $cl");
213 elsif ($type eq "GLOB") {
216 my $val = _dump($$rval, $name, [@$idx, "*"]);
218 if ($out =~ /^\\\*Symbol::/) {
220 $out = "Symbol::gensym()";
226 for my $k (qw(SCALAR ARRAY HASH)) {
227 my $gval = *$$rval{$k};
228 next unless defined $gval;
229 next if $k eq "SCALAR" && ! defined $$gval; # always there
230 my $f = scalar @fixup;
231 push(@fixup, "RESERVED"); # overwritten after _dump() below
232 $gval = _dump($gval, $name, [@$idx, "*{$k}"]);
234 my $gname = fullname($name, $idx);
235 $fixup[$f] = "$gname = $gval"; #XXX indent $gval
239 elsif ($type eq "ARRAY") {
241 my $tied = tied_str(tied(@$rval));
244 push(@vals, _dump($v, $name, [@$idx, "[$i]"], $tied));
247 $out = "[" . format_list(1, $tied, @vals) . "]";
249 elsif ($type eq "HASH") {
251 my $tied = tied_str(tied(%$rval));
253 # statistics to determine variation in key lengths
258 my @orig_keys = keys %$rval;
261 $text_keys++, last unless /^[-+]?(?:0|[1-9]\d*)(?:\.\d+)?\z/;
265 @orig_keys = sort @orig_keys;
268 @orig_keys = sort { $a <=> $b } @orig_keys;
271 for my $key (@orig_keys) {
272 my $val = \$rval->{$key};
273 $key = quote($key) if $is_perl_keyword{$key} ||
274 !($key =~ /^[a-zA-Z_]\w{0,19}\z/ ||
275 $key =~ /^-?[1-9]\d{0,8}\z/
278 $kstat_max = length($key) if length($key) > $kstat_max;
279 $kstat_sum += length($key);
280 $kstat_sum2 += length($key)*length($key);
283 push(@vals, _dump($$val, $name, [@$idx, "{$key}"], $tied));
287 my $tmp = "@keys @vals";
288 if (length($tmp) > 60 || $tmp =~ /\n/ || $tied) {
291 # Determine what padding to add
292 if ($kstat_max < 4) {
293 $klen_pad = $kstat_max;
297 my $avg = $kstat_sum/$n;
298 my $stddev = sqrt(($kstat_sum2 - $n * $avg * $avg) / ($n - 1));
300 # I am not actually very happy with this heuristics
301 if ($stddev / $kstat_max < 0.25) {
302 $klen_pad = $kstat_max;
306 push(@vals, sprintf("%.2f (%d/%.1f/%.1f)",
307 $stddev / $kstat_max,
308 $kstat_max, $avg, $stddev));
313 $out .= " # $tied$nl" if $tied;
315 my $key = shift @keys;
316 my $val = shift @vals;
317 my $pad = " " x ($klen_pad + 6);
318 $val =~ s/\n/\n$pad/gm;
319 $key = " $key" . " " x ($klen_pad - length($key)) if $nl;
320 $out .= " $key => $val,$nl";
322 $out =~ s/,$/ / unless $nl;
325 elsif ($type eq "CODE") {
326 $out = 'sub { "???" }';
329 warn "Can't handle $type data";
333 if ($class && $ref) {
334 $out = "bless($out, " . quote($class) . ")";
342 if (my $tied_ref = ref($tied)) {
343 $tied = "tied $tied_ref";
354 my($name, $idx, $ref) = @_;
355 substr($name, 0, 0) = "\$";
357 my @i = @$idx; # need copy in order to not modify @$idx
358 if ($ref && @i && $i[0] eq "\$") {
359 shift(@i); # remove one deref
362 while (@i && $i[0] eq "\$") {
369 if ($i eq "*" || $i eq "\$") {
371 $name = "$i\{$name}";
372 } elsif ($i =~ s/^\*//) {
376 $name .= "->" unless $last_was_index++;
380 $name = "\\$name" if $ref;
388 my $indent_lim = $paren ? 0 : 1;
390 if ($comment || (@_ > $indent_lim && (length($tmp) > 60 || $tmp =~ /\n/))) {
392 for (@elem) { s/^/ /gm; } # indent
393 return "\n" . ($comment ? " # $comment\n" : "") .
394 join(",\n", @elem, "");
396 return join(", ", @_);
401 if (length($_[0]) > 20) {
403 # Check for repeated string
405 # seems to be a repating sequence, let's check if it really is
406 # without backtracking
407 unless (/[^\Q$1\E]/) {
408 my $base = quote($1);
410 return "($base x $repeat)"
413 # Length protection because the RE engine will blow the stack [RT#33520]
414 if (length($_) < 16 * 1024 && /^(.{2,5}?)\1*\z/s) {
415 my $base = quote($1);
416 my $repeat = length($_)/length($1);
417 return "($base x $repeat)";
424 if (length($_) > 40 && !/\\x\{/ && length($_) > (length($_[0]) * 2)) {
425 # too much binary data, better to represent as a hex/base64 string
427 # Base64 is more compact than hex when string is longer than
428 # 17 bytes (not counting any require statement needed).
429 # But on the other hand, hex is much more readable.
430 if ($TRY_BASE64 && length($_[0]) > $TRY_BASE64 &&
431 eval { require MIME::Base64 })
433 $require{"MIME::Base64"}++;
434 return "MIME::Base64::decode(\"" .
435 MIME::Base64::encode($_[0],"") .
438 return "pack(\"H*\",\"" . unpack("H*", $_[0]) . "\")";
454 # put a string value in double quotes
457 # If there are many '"' we might want to use qq() instead
458 s/([\\\"\@\$])/\\$1/g;
459 return qq("$_") unless /[^\040-\176]/; # fast exit
461 s/([\a\b\t\n\f\r\e])/$esc{$1}/g;
463 # no need for 3 digits in escape for these
464 s/([\0-\037])(?!\d)/sprintf('\\%o',ord($1))/eg;
466 s/([\0-\037\177-\377])/sprintf('\\x%02X',ord($1))/eg;
467 s/([^\040-\176])/sprintf('\\x{%X}',ord($1))/eg;
478 Data::Dump - Pretty printing of data structures
482 use Data::Dump qw(dump ddx);
485 @copy_of_list = eval $str;
487 # or use it for easy debug printout
492 This module provide functions that takes a list of values as their
493 argument and produces a string as its result. The string contains
494 Perl code that, when C<eval>ed, produces a deep copy of the original
497 The main feature of the module is that it strives to produce output
498 that is easy to read. Example:
500 @a = (1, [2, 3], {4 => 5});
505 (1, [2, 3], { 4 => 5 })
507 If you dump just a little data, it is output on a single line. If
508 you dump data that is more complex or there is a lot of it, line breaks
509 are automatically added to keep it easy to read.
511 The following functions are provided (only the dd* functions are exported by default):
519 Returns a string containing a Perl expression. If you pass this
520 string to Perl's built-in eval() function it should return a copy of
521 the arguments you passed to dump().
523 If you call the function with multiple arguments then the output will
524 be wrapped in parenthesis "( ..., ... )". If you call the function with a
525 single argument the output will not have the wrapping. If you call the function with
526 a single scalar (non-reference) argument it will just return the
527 scalar quoted if needed, but never break it into multiple lines. If you
528 pass multiple arguments or references to arrays of hashes then the
529 return value might contain line breaks to format it for easier
530 reading. The returned string will never be "\n" terminated, even if
531 contains multiple lines. This allows code like this to place the
532 semicolon in the expected place:
534 print '$obj = ', dump($obj), ";\n";
536 If dump() is called in void context, then the dump is printed on
537 STDERR and then "\n" terminated. You might find this useful for quick
538 debug printouts, but the dd*() functions might be better alternatives
541 There is no difference between dump() and pp(), except that dump()
542 shares its name with a not-so-useful perl builtin. Because of this
543 some might want to avoid using that name.
545 =item quote( $string )
547 Returns a quoted version of the provided string.
549 It differs from C<dump($string)> in that it will quote even numbers and
550 not try to come up with clever expressions that might shorten the
557 These functions will call dump() on their argument and print the
558 result to STDOUT (actually, it's the currently selected output handle, but
559 STDOUT is the default for that).
561 The difference between them is only that ddx() will prefix the lines
562 it prints with "# " and mark the first line with the file and line
563 number where it was called. This is meant to be useful for debug
564 printouts of state within programs.
571 Code references will be displayed as simply 'sub { "???" }' when
572 dumped. Thus, C<eval>ing them will not reproduce the original routine.
574 If you forget to explicitly import the C<dump> function, your code will
575 core dump. That's because you just called the builtin C<dump> function
576 by accident, which intentionally dumps core. Because of this you can
577 also import the same function as C<pp>, mnemonic for "pretty-print".
581 The C<Data::Dump> module grew out of frustration with Sarathy's
582 in-most-cases-excellent C<Data::Dumper>. Basic ideas and some code
583 are shared with Sarathy's module.
585 The C<Data::Dump> module provides a much simpler interface than
586 C<Data::Dumper>. No OO interface is available and there are no
587 configuration options to worry about (yet :-). The other benefit is
588 that the dump produced does not try to set any variables. It only
589 returns what is needed to produce a copy of the arguments. This means
590 that C<dump("foo")> simply returns C<"foo">, and C<dump(1..5)> simply
591 returns C<(1, 2, 3, 4, 5)>.
595 L<Data::Dumper>, L<Storable>
599 The C<Data::Dump> module is written by Gisle Aas <gisle@aas.no>, based
600 on C<Data::Dumper> by Gurusamy Sarathy <gsar@umich.edu>.
602 Copyright 1998-2000,2003-2004,2008 Gisle Aas.
603 Copyright 1996-1998 Gurusamy Sarathy.
605 This library is free software; you can redistribute it and/or
606 modify it under the same terms as Perl itself.