Integrate mainline + lib/open.t patch from Chromatic
[p5sagit/p5-mst-13.2.git] / ext / Data / Dumper / Dumper.pm
CommitLineData
823edd99 1#
2# Data/Dumper.pm
3#
4# convert perl data structures into perl syntax suitable for both printing
5# and eval
6#
7# Documentation at the __END__
8#
9
10package Data::Dumper;
11
88d01e8d 12$VERSION = '2.103';
823edd99 13
14#$| = 1;
15
3b825e41 16use 5.006_001;
823edd99 17require Exporter;
9426adcd 18use XSLoader ();
823edd99 19require overload;
20
21use Carp;
22
9426adcd 23@ISA = qw(Exporter);
823edd99 24@EXPORT = qw(Dumper);
25@EXPORT_OK = qw(DumperX);
26
9426adcd 27XSLoader::load 'Data::Dumper';
823edd99 28
29# module vars and their defaults
30$Indent = 2 unless defined $Indent;
31$Purity = 0 unless defined $Purity;
32$Pad = "" unless defined $Pad;
33$Varname = "VAR" unless defined $Varname;
34$Useqq = 0 unless defined $Useqq;
35$Terse = 0 unless defined $Terse;
36$Freezer = "" unless defined $Freezer;
37$Toaster = "" unless defined $Toaster;
38$Deepcopy = 0 unless defined $Deepcopy;
39$Quotekeys = 1 unless defined $Quotekeys;
40$Bless = "bless" unless defined $Bless;
41#$Expdepth = 0 unless defined $Expdepth;
a2126434 42$Maxdepth = 0 unless defined $Maxdepth;
31a725b3 43$Useperl = 0 unless defined $Useperl;
44$Sortkeys = 0 unless defined $Sortkeys;
823edd99 45
46#
47# expects an arrayref of values to be dumped.
48# can optionally pass an arrayref of names for the values.
49# names must have leading $ sign stripped. begin the name with *
50# to cause output of arrays and hashes rather than refs.
51#
52sub new {
53 my($c, $v, $n) = @_;
54
55 croak "Usage: PACKAGE->new(ARRAYREF, [ARRAYREF])"
56 unless (defined($v) && (ref($v) eq 'ARRAY'));
57 $n = [] unless (defined($n) && (ref($v) eq 'ARRAY'));
58
59 my($s) = {
60 level => 0, # current recursive depth
61 indent => $Indent, # various styles of indenting
62 pad => $Pad, # all lines prefixed by this string
63 xpad => "", # padding-per-level
64 apad => "", # added padding for hash keys n such
65 sep => "", # list separator
66 seen => {}, # local (nested) refs (id => [name, val])
67 todump => $v, # values to dump []
68 names => $n, # optional names for values []
69 varname => $Varname, # prefix to use for tagging nameless ones
70 purity => $Purity, # degree to which output is evalable
71 useqq => $Useqq, # use "" for strings (backslashitis ensues)
72 terse => $Terse, # avoid name output (where feasible)
73 freezer => $Freezer, # name of Freezer method for objects
74 toaster => $Toaster, # name of method to revive objects
75 deepcopy => $Deepcopy, # dont cross-ref, except to stop recursion
76 quotekeys => $Quotekeys, # quote hash keys
77 'bless' => $Bless, # keyword to use for "bless"
78# expdepth => $Expdepth, # cutoff depth for explicit dumping
a2126434 79 maxdepth => $Maxdepth, # depth beyond which we give up
31a725b3 80 useperl => $Useperl, # use the pure Perl implementation
81 sortkeys => $Sortkeys, # flag or filter for sorting hash keys
823edd99 82 };
83
84 if ($Indent > 0) {
85 $s->{xpad} = " ";
86 $s->{sep} = "\n";
87 }
88 return bless($s, $c);
89}
90
91#
92# add-to or query the table of already seen references
93#
94sub Seen {
95 my($s, $g) = @_;
96 if (defined($g) && (ref($g) eq 'HASH')) {
97 my($k, $v, $id);
98 while (($k, $v) = each %$g) {
99 if (defined $v and ref $v) {
100 ($id) = (overload::StrVal($v) =~ /\((.*)\)$/);
101 if ($k =~ /^[*](.*)$/) {
102 $k = (ref $v eq 'ARRAY') ? ( "\\\@" . $1 ) :
103 (ref $v eq 'HASH') ? ( "\\\%" . $1 ) :
104 (ref $v eq 'CODE') ? ( "\\\&" . $1 ) :
105 ( "\$" . $1 ) ;
106 }
107 elsif ($k !~ /^\$/) {
108 $k = "\$" . $k;
109 }
110 $s->{seen}{$id} = [$k, $v];
111 }
112 else {
113 carp "Only refs supported, ignoring non-ref item \$$k";
114 }
115 }
116 return $s;
117 }
118 else {
119 return map { @$_ } values %{$s->{seen}};
120 }
121}
122
123#
124# set or query the values to be dumped
125#
126sub Values {
127 my($s, $v) = @_;
128 if (defined($v) && (ref($v) eq 'ARRAY')) {
129 $s->{todump} = [@$v]; # make a copy
130 return $s;
131 }
132 else {
133 return @{$s->{todump}};
134 }
135}
136
137#
138# set or query the names of the values to be dumped
139#
140sub Names {
141 my($s, $n) = @_;
142 if (defined($n) && (ref($n) eq 'ARRAY')) {
143 $s->{names} = [@$n]; # make a copy
144 return $s;
145 }
146 else {
147 return @{$s->{names}};
148 }
149}
150
151sub DESTROY {}
152
0f1923bd 153sub Dump {
154 return &Dumpxs
31a725b3 155 unless $Data::Dumper::Useperl || (ref($_[0]) && $_[0]->{useperl}) ||
156 $Data::Dumper::Useqq || (ref($_[0]) && $_[0]->{useqq});
0f1923bd 157 return &Dumpperl;
158}
159
823edd99 160#
161# dump the refs in the current dumper object.
162# expects same args as new() if called via package name.
163#
0f1923bd 164sub Dumpperl {
823edd99 165 my($s) = shift;
166 my(@out, $val, $name);
167 my($i) = 0;
168 local(@post);
169
170 $s = $s->new(@_) unless ref $s;
171
172 for $val (@{$s->{todump}}) {
173 my $out = "";
174 @post = ();
175 $name = $s->{names}[$i++];
176 if (defined $name) {
177 if ($name =~ /^[*](.*)$/) {
178 if (defined $val) {
179 $name = (ref $val eq 'ARRAY') ? ( "\@" . $1 ) :
180 (ref $val eq 'HASH') ? ( "\%" . $1 ) :
181 (ref $val eq 'CODE') ? ( "\*" . $1 ) :
182 ( "\$" . $1 ) ;
183 }
184 else {
185 $name = "\$" . $1;
186 }
187 }
188 elsif ($name !~ /^\$/) {
189 $name = "\$" . $name;
190 }
191 }
192 else {
193 $name = "\$" . $s->{varname} . $i;
194 }
195
196 my $valstr;
197 {
198 local($s->{apad}) = $s->{apad};
199 $s->{apad} .= ' ' x (length($name) + 3) if $s->{indent} >= 2;
200 $valstr = $s->_dump($val, $name);
201 }
202
203 $valstr = "$name = " . $valstr . ';' if @post or !$s->{terse};
204 $out .= $s->{pad} . $valstr . $s->{sep};
205 $out .= $s->{pad} . join(';' . $s->{sep} . $s->{pad}, @post)
206 . ';' . $s->{sep} if @post;
207
208 push @out, $out;
209 }
210 return wantarray ? @out : join('', @out);
211}
212
213#
214# twist, toil and turn;
215# and recurse, of course.
31a725b3 216# sometimes sordidly;
217# and curse if no recourse.
823edd99 218#
219sub _dump {
220 my($s, $val, $name) = @_;
221 my($sname);
222 my($out, $realpack, $realtype, $type, $ipad, $id, $blesspad);
223
823edd99 224 $type = ref $val;
225 $out = "";
226
227 if ($type) {
228
229 # prep it, if it looks like an object
982af928 230 if (my $freezer = $s->{freezer}) {
231 $val->$freezer() if UNIVERSAL::can($val, $freezer);
823edd99 232 }
233
234 ($realpack, $realtype, $id) =
235 (overload::StrVal($val) =~ /^(?:(.*)\=)?([^=]*)\(([^\(]*)\)$/);
a2126434 236
7820172a 237 # if it has a name, we need to either look it up, or keep a tab
238 # on it so we know when we hit it later
239 if (defined($name) and length($name)) {
240 # keep a tab on it so that we dont fall into recursive pit
241 if (exists $s->{seen}{$id}) {
242# if ($s->{expdepth} < $s->{level}) {
243 if ($s->{purity} and $s->{level} > 0) {
244 $out = ($realtype eq 'HASH') ? '{}' :
245 ($realtype eq 'ARRAY') ? '[]' :
5df59fb6 246 'do{my $o}' ;
7820172a 247 push @post, $name . " = " . $s->{seen}{$id}[0];
823edd99 248 }
249 else {
7820172a 250 $out = $s->{seen}{$id}[0];
251 if ($name =~ /^([\@\%])/) {
252 my $start = $1;
253 if ($out =~ /^\\$start/) {
254 $out = substr($out, 1);
255 }
256 else {
257 $out = $start . '{' . $out . '}';
258 }
259 }
260 }
261 return $out;
262# }
263 }
264 else {
265 # store our name
266 $s->{seen}{$id} = [ (($name =~ /^[@%]/) ? ('\\' . $name ) :
267 ($realtype eq 'CODE' and
268 $name =~ /^[*](.*)$/) ? ('\\&' . $1 ) :
269 $name ),
270 $val ];
823edd99 271 }
823edd99 272 }
273
a2126434 274 if ($realpack and $realpack eq 'Regexp') {
7894fbab 275 $out = "$val";
276 $out =~ s,/,\\/,g;
277 return "qr/$out/";
a2126434 278 }
279
280 # If purity is not set and maxdepth is set, then check depth:
281 # if we have reached maximum depth, return the string
282 # representation of the thing we are currently examining
283 # at this depth (i.e., 'Foo=ARRAY(0xdeadbeef)').
284 if (!$s->{purity}
285 and $s->{maxdepth} > 0
286 and $s->{level} >= $s->{maxdepth})
287 {
288 return qq['$val'];
289 }
290
291 # we have a blessed ref
292 if ($realpack) {
293 $out = $s->{'bless'} . '( ';
294 $blesspad = $s->{apad};
295 $s->{apad} .= ' ' if ($s->{indent} >= 2);
7894fbab 296 }
297
823edd99 298 $s->{level}++;
299 $ipad = $s->{xpad} x $s->{level};
300
54964f74 301 if ($realtype eq 'SCALAR' || $realtype eq 'REF') {
823edd99 302 if ($realpack) {
7820172a 303 $out .= 'do{\\(my $o = ' . $s->_dump($$val, "\${$name}") . ')}';
823edd99 304 }
305 else {
7820172a 306 $out .= '\\' . $s->_dump($$val, "\${$name}");
823edd99 307 }
308 }
309 elsif ($realtype eq 'GLOB') {
7820172a 310 $out .= '\\' . $s->_dump($$val, "*{$name}");
823edd99 311 }
312 elsif ($realtype eq 'ARRAY') {
313 my($v, $pad, $mname);
314 my($i) = 0;
315 $out .= ($name =~ /^\@/) ? '(' : '[';
316 $pad = $s->{sep} . $s->{pad} . $s->{apad};
317 ($name =~ /^\@(.*)$/) ? ($mname = "\$" . $1) :
7820172a 318 # omit -> if $foo->[0]->{bar}, but not ${$foo->[0]}->{bar}
319 ($name =~ /^\\?[\%\@\*\$][^{].*[]}]$/) ? ($mname = $name) :
320 ($mname = $name . '->');
823edd99 321 $mname .= '->' if $mname =~ /^\*.+\{[A-Z]+\}$/;
322 for $v (@$val) {
323 $sname = $mname . '[' . $i . ']';
324 $out .= $pad . $ipad . '#' . $i if $s->{indent} >= 3;
325 $out .= $pad . $ipad . $s->_dump($v, $sname);
326 $out .= "," if $i++ < $#$val;
327 }
328 $out .= $pad . ($s->{xpad} x ($s->{level} - 1)) if $i;
329 $out .= ($name =~ /^\@/) ? ')' : ']';
330 }
331 elsif ($realtype eq 'HASH') {
332 my($k, $v, $pad, $lpad, $mname);
333 $out .= ($name =~ /^\%/) ? '(' : '{';
334 $pad = $s->{sep} . $s->{pad} . $s->{apad};
335 $lpad = $s->{apad};
7820172a 336 ($name =~ /^\%(.*)$/) ? ($mname = "\$" . $1) :
337 # omit -> if $foo->[0]->{bar}, but not ${$foo->[0]}->{bar}
338 ($name =~ /^\\?[\%\@\*\$][^{].*[]}]$/) ? ($mname = $name) :
339 ($mname = $name . '->');
823edd99 340 $mname .= '->' if $mname =~ /^\*.+\{[A-Z]+\}$/;
31a725b3 341 my ($sortkeys, $keys, $key) = ("$s->{sortkeys}");
342 if ($sortkeys) {
343 if (ref($s->{sortkeys}) eq 'CODE') {
344 $keys = $s->{sortkeys}($val);
345 unless (ref($keys) eq 'ARRAY') {
346 carp "Sortkeys subroutine did not return ARRAYREF";
347 $keys = [];
348 }
349 }
350 else {
351 $keys = [ sort keys %$val ];
352 }
353 }
354 while (($k, $v) = ! $sortkeys ? (each %$val) :
355 @$keys ? ($key = shift(@$keys), $val->{$key}) :
356 () )
357 {
823edd99 358 my $nk = $s->_dump($k, "");
359 $nk = $1 if !$s->{quotekeys} and $nk =~ /^[\"\']([A-Za-z_]\w*)[\"\']$/;
360 $sname = $mname . '{' . $nk . '}';
361 $out .= $pad . $ipad . $nk . " => ";
362
363 # temporarily alter apad
364 $s->{apad} .= (" " x (length($nk) + 4)) if $s->{indent} >= 2;
365 $out .= $s->_dump($val->{$k}, $sname) . ",";
366 $s->{apad} = $lpad if $s->{indent} >= 2;
367 }
368 if (substr($out, -1) eq ',') {
369 chop $out;
370 $out .= $pad . ($s->{xpad} x ($s->{level} - 1));
371 }
372 $out .= ($name =~ /^\%/) ? ')' : '}';
373 }
374 elsif ($realtype eq 'CODE') {
c8984b0b 375 $out .= 'sub { "DUMMY" }';
823edd99 376 carp "Encountered CODE ref, using dummy placeholder" if $s->{purity};
377 }
378 else {
379 croak "Can\'t handle $realtype type.";
380 }
381
382 if ($realpack) { # we have a blessed ref
383 $out .= ', \'' . $realpack . '\'' . ' )';
384 $out .= '->' . $s->{toaster} . '()' if $s->{toaster} ne '';
385 $s->{apad} = $blesspad;
386 }
387 $s->{level}--;
388
389 }
390 else { # simple scalar
391
392 my $ref = \$_[1];
393 # first, catalog the scalar
394 if ($name ne '') {
395 ($id) = ("$ref" =~ /\(([^\(]*)\)$/);
396 if (exists $s->{seen}{$id}) {
7820172a 397 if ($s->{seen}{$id}[2]) {
398 $out = $s->{seen}{$id}[0];
399 #warn "[<$out]\n";
400 return "\${$out}";
401 }
823edd99 402 }
403 else {
7820172a 404 #warn "[>\\$name]\n";
405 $s->{seen}{$id} = ["\\$name", $ref];
823edd99 406 }
407 }
408 if (ref($ref) eq 'GLOB' or "$ref" =~ /=GLOB\([^()]+\)$/) { # glob
409 my $name = substr($val, 1);
410 if ($name =~ /^[A-Za-z_][\w:]*$/) {
411 $name =~ s/^main::/::/;
412 $sname = $name;
413 }
414 else {
415 $sname = $s->_dump($name, "");
416 $sname = '{' . $sname . '}';
417 }
418 if ($s->{purity}) {
419 my $k;
420 local ($s->{level}) = 0;
421 for $k (qw(SCALAR ARRAY HASH)) {
7820172a 422 my $gval = *$val{$k};
423 next unless defined $gval;
424 next if $k eq "SCALAR" && ! defined $$gval; # always there
425
823edd99 426 # _dump can push into @post, so we hold our place using $postlen
427 my $postlen = scalar @post;
428 $post[$postlen] = "\*$sname = ";
429 local ($s->{apad}) = " " x length($post[$postlen]) if $s->{indent} >= 2;
7820172a 430 $post[$postlen] .= $s->_dump($gval, "\*$sname\{$k\}");
823edd99 431 }
432 }
433 $out .= '*' . $sname;
434 }
7820172a 435 elsif (!defined($val)) {
436 $out .= "undef";
437 }
45b49486 438 elsif ($val =~ /^(?:0|-?[1-9]\d{0,8})$/) { # safe decimal number
823edd99 439 $out .= $val;
440 }
441 else { # string
442 if ($s->{useqq}) {
7820172a 443 $out .= qquote($val, $s->{useqq});
823edd99 444 }
445 else {
446 $val =~ s/([\\\'])/\\$1/g;
447 $out .= '\'' . $val . '\'';
448 }
449 }
450 }
7820172a 451 if ($id) {
452 # if we made it this far, $id was added to seen list at current
453 # level, so remove it to get deep copies
454 if ($s->{deepcopy}) {
455 delete($s->{seen}{$id});
456 }
457 elsif ($name) {
458 $s->{seen}{$id}[2] = 1;
459 }
460 }
823edd99 461 return $out;
462}
463
464#
465# non-OO style of earlier version
466#
467sub Dumper {
468 return Data::Dumper->Dump([@_]);
469}
470
0f1923bd 471# compat stub
823edd99 472sub DumperX {
473 return Data::Dumper->Dumpxs([@_], []);
474}
475
476sub Dumpf { return Data::Dumper->Dump(@_) }
477
478sub Dumpp { print Data::Dumper->Dump(@_) }
479
480#
481# reset the "seen" cache
482#
483sub Reset {
484 my($s) = shift;
485 $s->{seen} = {};
486 return $s;
487}
488
489sub Indent {
490 my($s, $v) = @_;
491 if (defined($v)) {
492 if ($v == 0) {
493 $s->{xpad} = "";
494 $s->{sep} = "";
495 }
496 else {
497 $s->{xpad} = " ";
498 $s->{sep} = "\n";
499 }
500 $s->{indent} = $v;
501 return $s;
502 }
503 else {
504 return $s->{indent};
505 }
506}
507
508sub Pad {
509 my($s, $v) = @_;
510 defined($v) ? (($s->{pad} = $v), return $s) : $s->{pad};
511}
512
513sub Varname {
514 my($s, $v) = @_;
515 defined($v) ? (($s->{varname} = $v), return $s) : $s->{varname};
516}
517
518sub Purity {
519 my($s, $v) = @_;
520 defined($v) ? (($s->{purity} = $v), return $s) : $s->{purity};
521}
522
523sub Useqq {
524 my($s, $v) = @_;
525 defined($v) ? (($s->{useqq} = $v), return $s) : $s->{useqq};
526}
527
528sub Terse {
529 my($s, $v) = @_;
530 defined($v) ? (($s->{terse} = $v), return $s) : $s->{terse};
531}
532
533sub Freezer {
534 my($s, $v) = @_;
535 defined($v) ? (($s->{freezer} = $v), return $s) : $s->{freezer};
536}
537
538sub Toaster {
539 my($s, $v) = @_;
540 defined($v) ? (($s->{toaster} = $v), return $s) : $s->{toaster};
541}
542
543sub Deepcopy {
544 my($s, $v) = @_;
545 defined($v) ? (($s->{deepcopy} = $v), return $s) : $s->{deepcopy};
546}
547
548sub Quotekeys {
549 my($s, $v) = @_;
550 defined($v) ? (($s->{quotekeys} = $v), return $s) : $s->{quotekeys};
551}
552
553sub Bless {
554 my($s, $v) = @_;
555 defined($v) ? (($s->{'bless'} = $v), return $s) : $s->{'bless'};
556}
557
a2126434 558sub Maxdepth {
559 my($s, $v) = @_;
560 defined($v) ? (($s->{'maxdepth'} = $v), return $s) : $s->{'maxdepth'};
561}
562
31a725b3 563sub Useperl {
564 my($s, $v) = @_;
565 defined($v) ? (($s->{'useperl'} = $v), return $s) : $s->{'useperl'};
566}
567
568sub Sortkeys {
569 my($s, $v) = @_;
570 defined($v) ? (($s->{'sortkeys'} = $v), return $s) : $s->{'sortkeys'};
571}
572
a2126434 573
7820172a 574# used by qquote below
575my %esc = (
576 "\a" => "\\a",
577 "\b" => "\\b",
578 "\t" => "\\t",
579 "\n" => "\\n",
580 "\f" => "\\f",
581 "\r" => "\\r",
582 "\e" => "\\e",
583);
584
823edd99 585# put a string value in double quotes
586sub qquote {
587 local($_) = shift;
7820172a 588 s/([\\\"\@\$])/\\$1/g;
dc71dc59 589 my $bytes; { use bytes; $bytes = length }
590 s/([^\x00-\x7f])/'\x{'.sprintf("%x",ord($1)).'}'/ge if $bytes > length;
0407a77b 591 return qq("$_") unless
592 /[^ !"\#\$%&'()*+,\-.\/0-9:;<=>?\@A-Z[\\\]^_`a-z{|}~]/; # fast exit
7820172a 593
594 my $high = shift || "";
595 s/([\a\b\t\n\f\r\e])/$esc{$1}/g;
596
0407a77b 597 if (ord('^')==94) { # ascii
598 # no need for 3 digits in escape for these
599 s/([\0-\037])(?!\d)/'\\'.sprintf('%o',ord($1))/eg;
600 s/([\0-\037\177])/'\\'.sprintf('%03o',ord($1))/eg;
43948175 601 # all but last branch below not supported --BEHAVIOR SUBJECT TO CHANGE--
0407a77b 602 if ($high eq "iso8859") {
603 s/([\200-\240])/'\\'.sprintf('%o',ord($1))/eg;
604 } elsif ($high eq "utf8") {
605# use utf8;
606# $str =~ s/([^\040-\176])/sprintf "\\x{%04x}", ord($1)/ge;
607 } elsif ($high eq "8bit") {
608 # leave it as it is
609 } else {
610 s/([\200-\377])/'\\'.sprintf('%03o',ord($1))/eg;
611 }
612 }
613 else { # ebcdic
43948175 614 s{([^ !"\#\$%&'()*+,\-.\/0-9:;<=>?\@A-Z[\\\]^_`a-z{|}~])(?!\d)}
615 {my $v = ord($1); '\\'.sprintf(($v <= 037 ? '%o' : '%03o'), $v)}eg;
616 s{([^ !"\#\$%&'()*+,\-.\/0-9:;<=>?\@A-Z[\\\]^_`a-z{|}~])}
617 {'\\'.sprintf('%03o',ord($1))}eg;
7820172a 618 }
0407a77b 619
7820172a 620 return qq("$_");
823edd99 621}
622
6231;
624__END__
625
626=head1 NAME
627
628Data::Dumper - stringified perl data structures, suitable for both printing and C<eval>
629
823edd99 630=head1 SYNOPSIS
631
632 use Data::Dumper;
633
634 # simple procedural interface
635 print Dumper($foo, $bar);
636
637 # extended usage with names
638 print Data::Dumper->Dump([$foo, $bar], [qw(foo *ary)]);
639
640 # configuration variables
641 {
642 local $Data::Dump::Purity = 1;
643 eval Data::Dumper->Dump([$foo, $bar], [qw(foo *ary)]);
644 }
645
646 # OO usage
647 $d = Data::Dumper->new([$foo, $bar], [qw(foo *ary)]);
648 ...
649 print $d->Dump;
650 ...
651 $d->Purity(1)->Terse(1)->Deepcopy(1);
652 eval $d->Dump;
653
654
655=head1 DESCRIPTION
656
657Given a list of scalars or reference variables, writes out their contents in
658perl syntax. The references can also be objects. The contents of each
659variable is output in a single Perl statement. Handles self-referential
660structures correctly.
661
662The return value can be C<eval>ed to get back an identical copy of the
663original reference structure.
664
665Any references that are the same as one of those passed in will be named
666C<$VAR>I<n> (where I<n> is a numeric suffix), and other duplicate references
667to substructures within C<$VAR>I<n> will be appropriately labeled using arrow
668notation. You can specify names for individual values to be dumped if you
669use the C<Dump()> method, or you can change the default C<$VAR> prefix to
670something else. See C<$Data::Dumper::Varname> and C<$Data::Dumper::Terse>
671below.
672
673The default output of self-referential structures can be C<eval>ed, but the
674nested references to C<$VAR>I<n> will be undefined, since a recursive
675structure cannot be constructed using one Perl statement. You should set the
676C<Purity> flag to 1 to get additional statements that will correctly fill in
677these references.
678
679In the extended usage form, the references to be dumped can be given
680user-specified names. If a name begins with a C<*>, the output will
681describe the dereferenced type of the supplied reference for hashes and
682arrays, and coderefs. Output of names will be avoided where possible if
683the C<Terse> flag is set.
684
685In many cases, methods that are used to set the internal state of the
686object will return the object itself, so method calls can be conveniently
687chained together.
688
689Several styles of output are possible, all controlled by setting
690the C<Indent> flag. See L<Configuration Variables or Methods> below
691for details.
692
693
694=head2 Methods
695
696=over 4
697
698=item I<PACKAGE>->new(I<ARRAYREF [>, I<ARRAYREF]>)
699
700Returns a newly created C<Data::Dumper> object. The first argument is an
701anonymous array of values to be dumped. The optional second argument is an
702anonymous array of names for the values. The names need not have a leading
703C<$> sign, and must be comprised of alphanumeric characters. You can begin
704a name with a C<*> to specify that the dereferenced type must be dumped
705instead of the reference itself, for ARRAY and HASH references.
706
707The prefix specified by C<$Data::Dumper::Varname> will be used with a
708numeric suffix if the name for a value is undefined.
709
710Data::Dumper will catalog all references encountered while dumping the
711values. Cross-references (in the form of names of substructures in perl
712syntax) will be inserted at all possible points, preserving any structural
713interdependencies in the original set of values. Structure traversal is
714depth-first, and proceeds in order from the first supplied value to
715the last.
716
717=item I<$OBJ>->Dump I<or> I<PACKAGE>->Dump(I<ARRAYREF [>, I<ARRAYREF]>)
718
719Returns the stringified form of the values stored in the object (preserving
720the order in which they were supplied to C<new>), subject to the
91e74348 721configuration options below. In a list context, it returns a list
823edd99 722of strings corresponding to the supplied values.
723
724The second form, for convenience, simply calls the C<new> method on its
725arguments before dumping the object immediately.
726
823edd99 727=item I<$OBJ>->Seen(I<[HASHREF]>)
728
729Queries or adds to the internal table of already encountered references.
730You must use C<Reset> to explicitly clear the table if needed. Such
731references are not dumped; instead, their names are inserted wherever they
732are encountered subsequently. This is useful especially for properly
733dumping subroutine references.
734
735Expects a anonymous hash of name => value pairs. Same rules apply for names
736as in C<new>. If no argument is supplied, will return the "seen" list of
91e74348 737name => value pairs, in a list context. Otherwise, returns the object
823edd99 738itself.
739
740=item I<$OBJ>->Values(I<[ARRAYREF]>)
741
742Queries or replaces the internal array of values that will be dumped.
743When called without arguments, returns the values. Otherwise, returns the
744object itself.
745
746=item I<$OBJ>->Names(I<[ARRAYREF]>)
747
748Queries or replaces the internal array of user supplied names for the values
749that will be dumped. When called without arguments, returns the names.
750Otherwise, returns the object itself.
751
752=item I<$OBJ>->Reset
753
754Clears the internal table of "seen" references and returns the object
755itself.
756
757=back
758
759=head2 Functions
760
761=over 4
762
763=item Dumper(I<LIST>)
764
765Returns the stringified form of the values in the list, subject to the
766configuration options below. The values will be named C<$VAR>I<n> in the
767output, where I<n> is a numeric suffix. Will return a list of strings
91e74348 768in a list context.
823edd99 769
823edd99 770=back
771
772=head2 Configuration Variables or Methods
773
774Several configuration variables can be used to control the kind of output
775generated when using the procedural interface. These variables are usually
776C<local>ized in a block so that other parts of the code are not affected by
777the change.
778
779These variables determine the default state of the object created by calling
780the C<new> method, but cannot be used to alter the state of the object
781thereafter. The equivalent method names should be used instead to query
782or set the internal state of the object.
783
784The method forms return the object itself when called with arguments,
785so that they can be chained together nicely.
786
787=over 4
788
789=item $Data::Dumper::Indent I<or> I<$OBJ>->Indent(I<[NEWVAL]>)
790
791Controls the style of indentation. It can be set to 0, 1, 2 or 3. Style 0
792spews output without any newlines, indentation, or spaces between list
793items. It is the most compact format possible that can still be called
794valid perl. Style 1 outputs a readable form with newlines but no fancy
795indentation (each level in the structure is simply indented by a fixed
796amount of whitespace). Style 2 (the default) outputs a very readable form
797which takes into account the length of hash keys (so the hash value lines
798up). Style 3 is like style 2, but also annotates the elements of arrays
799with their index (but the comment is on its own line, so array output
800consumes twice the number of lines). Style 2 is the default.
801
802=item $Data::Dumper::Purity I<or> I<$OBJ>->Purity(I<[NEWVAL]>)
803
804Controls the degree to which the output can be C<eval>ed to recreate the
805supplied reference structures. Setting it to 1 will output additional perl
806statements that will correctly recreate nested references. The default is
8070.
808
809=item $Data::Dumper::Pad I<or> I<$OBJ>->Pad(I<[NEWVAL]>)
810
811Specifies the string that will be prefixed to every line of the output.
812Empty string by default.
813
814=item $Data::Dumper::Varname I<or> I<$OBJ>->Varname(I<[NEWVAL]>)
815
816Contains the prefix to use for tagging variable names in the output. The
817default is "VAR".
818
819=item $Data::Dumper::Useqq I<or> I<$OBJ>->Useqq(I<[NEWVAL]>)
820
821When set, enables the use of double quotes for representing string values.
822Whitespace other than space will be represented as C<[\n\t\r]>, "unsafe"
823characters will be backslashed, and unprintable characters will be output as
824quoted octal integers. Since setting this variable imposes a performance
0f1923bd 825penalty, the default is 0. C<Dump()> will run slower if this flag is set,
826since the fast XSUB implementation doesn't support it yet.
823edd99 827
828=item $Data::Dumper::Terse I<or> I<$OBJ>->Terse(I<[NEWVAL]>)
829
830When set, Data::Dumper will emit single, non-self-referential values as
831atoms/terms rather than statements. This means that the C<$VAR>I<n> names
832will be avoided where possible, but be advised that such output may not
833always be parseable by C<eval>.
834
835=item $Data::Dumper::Freezer I<or> $I<OBJ>->Freezer(I<[NEWVAL]>)
836
837Can be set to a method name, or to an empty string to disable the feature.
838Data::Dumper will invoke that method via the object before attempting to
839stringify it. This method can alter the contents of the object (if, for
840instance, it contains data allocated from C), and even rebless it in a
841different package. The client is responsible for making sure the specified
842method can be called via the object, and that the object ends up containing
843only perl data types after the method has been called. Defaults to an empty
844string.
845
846=item $Data::Dumper::Toaster I<or> $I<OBJ>->Toaster(I<[NEWVAL]>)
847
848Can be set to a method name, or to an empty string to disable the feature.
849Data::Dumper will emit a method call for any objects that are to be dumped
850using the syntax C<bless(DATA, CLASS)->METHOD()>. Note that this means that
851the method specified will have to perform any modifications required on the
852object (like creating new state within it, and/or reblessing it in a
853different package) and then return it. The client is responsible for making
854sure the method can be called via the object, and that it returns a valid
855object. Defaults to an empty string.
856
857=item $Data::Dumper::Deepcopy I<or> $I<OBJ>->Deepcopy(I<[NEWVAL]>)
858
859Can be set to a boolean value to enable deep copies of structures.
860Cross-referencing will then only be done when absolutely essential
861(i.e., to break reference cycles). Default is 0.
862
863=item $Data::Dumper::Quotekeys I<or> $I<OBJ>->Quotekeys(I<[NEWVAL]>)
864
865Can be set to a boolean value to control whether hash keys are quoted.
866A false value will avoid quoting hash keys when it looks like a simple
867string. Default is 1, which will always enclose hash keys in quotes.
868
869=item $Data::Dumper::Bless I<or> $I<OBJ>->Bless(I<[NEWVAL]>)
870
871Can be set to a string that specifies an alternative to the C<bless>
872builtin operator used to create objects. A function with the specified
873name should exist, and should accept the same arguments as the builtin.
874Default is C<bless>.
875
a2126434 876=item $Data::Dumper::Maxdepth I<or> $I<OBJ>->Maxdepth(I<[NEWVAL]>)
877
878Can be set to a positive integer that specifies the depth beyond which
879which we don't venture into a structure. Has no effect when
880C<Data::Dumper::Purity> is set. (Useful in debugger when we often don't
881want to see more than enough). Default is 0, which means there is
882no maximum depth.
883
31a725b3 884=item $Data::Dumper::Useperl I<or> $I<OBJ>->Useperl(I<[NEWVAL]>)
885
886Can be set to a boolean value which controls whether the pure Perl
887implementation of C<Data::Dumper> is used. The C<Data::Dumper> module is
888a dual implementation, with almost all functionality written in both
889pure Perl and also in XS ('C'). Since the XS version is much faster, it
890will always be used if possible. This option lets you override the
891default behavior, usually for testing purposes only. Default is 0, which
892means the XS implementation will be used if possible.
893
894=item $Data::Dumper::Sortkeys I<or> $I<OBJ>->Sortkeys(I<[NEWVAL]>)
895
896Can be set to a boolean value to control whether hash keys are dumped in
897sorted order. A true value will cause the keys of all hashes to be
898dumped in Perl's default sort order. Can also be set to a subroutine
899reference which will be called for each hash that is dumped. In this
900case C<Data::Dumper> will call the subroutine once for each hash,
901passing it the reference of the hash. The purpose of the subroutine is
902to return a reference to an array of the keys that will be dumped, in
903the order that they should be dumped. Using this feature, you can
904control both the order of the keys, and which keys are actually used. In
905other words, this subroutine acts as a filter by which you can exclude
906certain keys from being dumped. Default is 0, which means that hash keys
907are not sorted.
908
823edd99 909=back
910
911=head2 Exports
912
913=over 4
914
915=item Dumper
916
917=back
918
919=head1 EXAMPLES
920
921Run these code snippets to get a quick feel for the behavior of this
922module. When you are through with these examples, you may want to
923add or change the various configuration variables described above,
924to see their behavior. (See the testsuite in the Data::Dumper
925distribution for more examples.)
926
927
928 use Data::Dumper;
929
930 package Foo;
931 sub new {bless {'a' => 1, 'b' => sub { return "foo" }}, $_[0]};
932
933 package Fuz; # a weird REF-REF-SCALAR object
934 sub new {bless \($_ = \ 'fu\'z'), $_[0]};
935
936 package main;
937 $foo = Foo->new;
938 $fuz = Fuz->new;
939 $boo = [ 1, [], "abcd", \*foo,
940 {1 => 'a', 023 => 'b', 0x45 => 'c'},
941 \\"p\q\'r", $foo, $fuz];
3cb6de81 942
823edd99 943 ########
944 # simple usage
945 ########
946
947 $bar = eval(Dumper($boo));
948 print($@) if $@;
949 print Dumper($boo), Dumper($bar); # pretty print (no array indices)
950
951 $Data::Dumper::Terse = 1; # don't output names where feasible
952 $Data::Dumper::Indent = 0; # turn off all pretty print
953 print Dumper($boo), "\n";
954
955 $Data::Dumper::Indent = 1; # mild pretty print
956 print Dumper($boo);
957
958 $Data::Dumper::Indent = 3; # pretty print with array indices
959 print Dumper($boo);
960
961 $Data::Dumper::Useqq = 1; # print strings in double quotes
962 print Dumper($boo);
3cb6de81 963
964
823edd99 965 ########
966 # recursive structures
967 ########
3cb6de81 968
823edd99 969 @c = ('c');
970 $c = \@c;
971 $b = {};
972 $a = [1, $b, $c];
973 $b->{a} = $a;
974 $b->{b} = $a->[1];
975 $b->{c} = $a->[2];
976 print Data::Dumper->Dump([$a,$b,$c], [qw(a b c)]);
3cb6de81 977
978
823edd99 979 $Data::Dumper::Purity = 1; # fill in the holes for eval
980 print Data::Dumper->Dump([$a, $b], [qw(*a b)]); # print as @a
981 print Data::Dumper->Dump([$b, $a], [qw(*b a)]); # print as %b
3cb6de81 982
983
823edd99 984 $Data::Dumper::Deepcopy = 1; # avoid cross-refs
985 print Data::Dumper->Dump([$b, $a], [qw(*b a)]);
3cb6de81 986
987
823edd99 988 $Data::Dumper::Purity = 0; # avoid cross-refs
989 print Data::Dumper->Dump([$b, $a], [qw(*b a)]);
3cb6de81 990
a2126434 991 ########
992 # deep structures
993 ########
3cb6de81 994
a2126434 995 $a = "pearl";
996 $b = [ $a ];
997 $c = { 'b' => $b };
998 $d = [ $c ];
999 $e = { 'd' => $d };
1000 $f = { 'e' => $e };
1001 print Data::Dumper->Dump([$f], [qw(f)]);
1002
1003 $Data::Dumper::Maxdepth = 3; # no deeper than 3 refs down
1004 print Data::Dumper->Dump([$f], [qw(f)]);
1005
3cb6de81 1006
823edd99 1007 ########
1008 # object-oriented usage
1009 ########
3cb6de81 1010
823edd99 1011 $d = Data::Dumper->new([$a,$b], [qw(a b)]);
1012 $d->Seen({'*c' => $c}); # stash a ref without printing it
1013 $d->Indent(3);
1014 print $d->Dump;
1015 $d->Reset->Purity(0); # empty the seen cache
1016 print join "----\n", $d->Dump;
3cb6de81 1017
1018
823edd99 1019 ########
1020 # persistence
1021 ########
3cb6de81 1022
823edd99 1023 package Foo;
1024 sub new { bless { state => 'awake' }, shift }
1025 sub Freeze {
1026 my $s = shift;
1027 print STDERR "preparing to sleep\n";
1028 $s->{state} = 'asleep';
1029 return bless $s, 'Foo::ZZZ';
1030 }
3cb6de81 1031
823edd99 1032 package Foo::ZZZ;
1033 sub Thaw {
1034 my $s = shift;
1035 print STDERR "waking up\n";
1036 $s->{state} = 'awake';
1037 return bless $s, 'Foo';
1038 }
3cb6de81 1039
823edd99 1040 package Foo;
1041 use Data::Dumper;
1042 $a = Foo->new;
1043 $b = Data::Dumper->new([$a], ['c']);
1044 $b->Freezer('Freeze');
1045 $b->Toaster('Thaw');
1046 $c = $b->Dump;
1047 print $c;
1048 $d = eval $c;
1049 print Data::Dumper->Dump([$d], ['d']);
3cb6de81 1050
1051
823edd99 1052 ########
1053 # symbol substitution (useful for recreating CODE refs)
1054 ########
3cb6de81 1055
823edd99 1056 sub foo { print "foo speaking\n" }
1057 *other = \&foo;
1058 $bar = [ \&other ];
1059 $d = Data::Dumper->new([\&other,$bar],['*other','bar']);
1060 $d->Seen({ '*foo' => \&foo });
1061 print $d->Dump;
1062
1063
31a725b3 1064 ########
1065 # sorting and filtering hash keys
1066 ########
1067
1068 $Data::Dumper::Sortkeys = \&my_filter;
1069 my $foo = { map { (ord, "$_$_$_") } 'I'..'Q' };
1070 my $bar = { %$foo };
1071 my $baz = { reverse %$foo };
1072 print Dumper [ $foo, $bar, $baz ];
1073
1074 sub my_filter {
1075 my ($hash) = @_;
1076 # return an array ref containing the hash keys to dump
1077 # in the order that you want them to be dumped
1078 return [
1079 # Sort the keys of %$foo in reverse numeric order
1080 $hash eq $foo ? (sort {$b <=> $a} keys %$hash) :
1081 # Only dump the odd number keys of %$bar
1082 $hash eq $bar ? (grep {$_ % 2} keys %$hash) :
1083 # Sort keys in default order for all other hashes
1084 (sort keys %$hash)
1085 ];
1086 }
1087
823edd99 1088=head1 BUGS
1089
1090Due to limitations of Perl subroutine call semantics, you cannot pass an
1091array or hash. Prepend it with a C<\> to pass its reference instead. This
1092will be remedied in time, with the arrival of prototypes in later versions
1093of Perl. For now, you need to use the extended usage form, and prepend the
1094name with a C<*> to output it as a hash or array.
1095
1096C<Data::Dumper> cheats with CODE references. If a code reference is
1097encountered in the structure being processed, an anonymous subroutine that
1098contains the string '"DUMMY"' will be inserted in its place, and a warning
1099will be printed if C<Purity> is set. You can C<eval> the result, but bear
1100in mind that the anonymous sub that gets created is just a placeholder.
1101Someday, perl will have a switch to cache-on-demand the string
1102representation of a compiled piece of code, I hope. If you have prior
1103knowledge of all the code refs that your data structures are likely
1104to have, you can use the C<Seen> method to pre-seed the internal reference
1105table and make the dumped output point to them, instead. See L<EXAMPLES>
1106above.
1107
0f1923bd 1108The C<Useqq> flag makes Dump() run slower, since the XSUB implementation
1109does not support it.
823edd99 1110
1111SCALAR objects have the weirdest looking C<bless> workaround.
1112
1113
1114=head1 AUTHOR
1115
6e238990 1116Gurusamy Sarathy gsar@activestate.com
823edd99 1117
1118Copyright (c) 1996-98 Gurusamy Sarathy. All rights reserved.
1119This program is free software; you can redistribute it and/or
1120modify it under the same terms as Perl itself.
1121
1122
1123=head1 VERSION
1124
a2126434 1125Version 2.11 (unreleased)
823edd99 1126
1127=head1 SEE ALSO
1128
1129perl(1)
1130
1131=cut