This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
Don't run stack_after_err.t on VMS.
[perl5.git] / dist / Data-Dumper / Dumper.pm
CommitLineData
823edd99
GS
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
d036e907 12BEGIN {
fb504317 13 $VERSION = '2.170'; # Don't forget to set version and release
3bd791fa 14} # date in POD below!
823edd99
GS
15
16#$| = 1;
17
3b825e41 18use 5.006_001;
823edd99 19require Exporter;
823edd99 20
e1416070
S
21use constant IS_PRE_520_PERL => $] < 5.020;
22
a261571f 23use Carp ();
823edd99 24
907e5114
JB
25BEGIN {
26 @ISA = qw(Exporter);
27 @EXPORT = qw(Dumper);
28 @EXPORT_OK = qw(DumperX);
823edd99 29
907e5114
JB
30 # if run under miniperl, or otherwise lacking dynamic loading,
31 # XSLoader should be attempted to load, or the pure perl flag
32 # toggled on load failure.
33 eval {
3bd791fa
JK
34 require XSLoader;
35 XSLoader::load( 'Data::Dumper' );
36 1
d036e907 37 }
1e9285c2 38 or $Useperl = 1;
907e5114 39}
823edd99 40
31ac59b6
KW
41my $IS_ASCII = ord 'A' == 65;
42
823edd99 43# module vars and their defaults
907e5114 44$Indent = 2 unless defined $Indent;
7089d392 45$Trailingcomma = 0 unless defined $Trailingcomma;
907e5114
JB
46$Purity = 0 unless defined $Purity;
47$Pad = "" unless defined $Pad;
48$Varname = "VAR" unless defined $Varname;
49$Useqq = 0 unless defined $Useqq;
50$Terse = 0 unless defined $Terse;
51$Freezer = "" unless defined $Freezer;
52$Toaster = "" unless defined $Toaster;
53$Deepcopy = 0 unless defined $Deepcopy;
54$Quotekeys = 1 unless defined $Quotekeys;
55$Bless = "bless" unless defined $Bless;
56#$Expdepth = 0 unless defined $Expdepth;
57$Maxdepth = 0 unless defined $Maxdepth;
58$Pair = ' => ' unless defined $Pair;
59$Useperl = 0 unless defined $Useperl;
60$Sortkeys = 0 unless defined $Sortkeys;
61$Deparse = 0 unless defined $Deparse;
d424882c 62$Sparseseen = 0 unless defined $Sparseseen;
19be3be6 63$Maxrecurse = 1000 unless defined $Maxrecurse;
823edd99
GS
64
65#
66# expects an arrayref of values to be dumped.
67# can optionally pass an arrayref of names for the values.
68# names must have leading $ sign stripped. begin the name with *
69# to cause output of arrays and hashes rather than refs.
70#
71sub new {
72 my($c, $v, $n) = @_;
73
a261571f 74 Carp::croak("Usage: PACKAGE->new(ARRAYREF, [ARRAYREF])")
823edd99 75 unless (defined($v) && (ref($v) eq 'ARRAY'));
b09a1111 76 $n = [] unless (defined($n) && (ref($n) eq 'ARRAY'));
823edd99 77
3bd791fa
JK
78 my($s) = {
79 level => 0, # current recursive depth
80 indent => $Indent, # various styles of indenting
7089d392 81 trailingcomma => $Trailingcomma, # whether to add comma after last elem
3bd791fa
JK
82 pad => $Pad, # all lines prefixed by this string
83 xpad => "", # padding-per-level
84 apad => "", # added padding for hash keys n such
85 sep => "", # list separator
86 pair => $Pair, # hash key/value separator: defaults to ' => '
87 seen => {}, # local (nested) refs (id => [name, val])
88 todump => $v, # values to dump []
89 names => $n, # optional names for values []
90 varname => $Varname, # prefix to use for tagging nameless ones
91 purity => $Purity, # degree to which output is evalable
92 useqq => $Useqq, # use "" for strings (backslashitis ensues)
93 terse => $Terse, # avoid name output (where feasible)
94 freezer => $Freezer, # name of Freezer method for objects
95 toaster => $Toaster, # name of method to revive objects
436d4ccf 96 deepcopy => $Deepcopy, # do not cross-ref, except to stop recursion
3bd791fa
JK
97 quotekeys => $Quotekeys, # quote hash keys
98 'bless' => $Bless, # keyword to use for "bless"
99# expdepth => $Expdepth, # cutoff depth for explicit dumping
100 maxdepth => $Maxdepth, # depth beyond which we give up
19be3be6 101 maxrecurse => $Maxrecurse, # depth beyond which we abort
3bd791fa
JK
102 useperl => $Useperl, # use the pure Perl implementation
103 sortkeys => $Sortkeys, # flag or filter for sorting hash keys
104 deparse => $Deparse, # use B::Deparse for coderefs
105 noseen => $Sparseseen, # do not populate the seen hash unless necessary
106 };
823edd99
GS
107
108 if ($Indent > 0) {
109 $s->{xpad} = " ";
110 $s->{sep} = "\n";
111 }
112 return bless($s, $c);
113}
114
53095d08 115# Packed numeric addresses take less memory. Plus pack is faster than sprintf
e52c0e5a 116
53095d08
NC
117# Most users of current versions of Data::Dumper will be 5.008 or later.
118# Anyone on 5.6.1 and 5.6.2 upgrading will be rare (particularly judging by
119# the bug reports from users on those platforms), so for the common case avoid
120# complexity, and avoid even compiling the unneeded code.
121
122sub init_refaddr_format {
123}
124
125sub format_refaddr {
e52c0e5a
NC
126 require Scalar::Util;
127 pack "J", Scalar::Util::refaddr(shift);
53095d08
NC
128};
129
130if ($] < 5.008) {
131 eval <<'EOC' or die;
132 no warnings 'redefine';
133 my $refaddr_format;
134 sub init_refaddr_format {
135 require Config;
136 my $f = $Config::Config{uvxformat};
137 $f =~ tr/"//d;
138 $refaddr_format = "0x%" . $f;
139 }
140
141 sub format_refaddr {
142 require Scalar::Util;
143 sprintf $refaddr_format, Scalar::Util::refaddr(shift);
144 }
145
146 1
147EOC
2728842d
RGS
148}
149
823edd99
GS
150#
151# add-to or query the table of already seen references
152#
153sub Seen {
154 my($s, $g) = @_;
155 if (defined($g) && (ref($g) eq 'HASH')) {
3b5b1125 156 init_refaddr_format();
823edd99
GS
157 my($k, $v, $id);
158 while (($k, $v) = each %$g) {
3bd791fa
JK
159 if (defined $v) {
160 if (ref $v) {
161 $id = format_refaddr($v);
162 if ($k =~ /^[*](.*)$/) {
163 $k = (ref $v eq 'ARRAY') ? ( "\\\@" . $1 ) :
164 (ref $v eq 'HASH') ? ( "\\\%" . $1 ) :
165 (ref $v eq 'CODE') ? ( "\\\&" . $1 ) :
166 ( "\$" . $1 ) ;
167 }
168 elsif ($k !~ /^\$/) {
169 $k = "\$" . $k;
170 }
171 $s->{seen}{$id} = [$k, $v];
172 }
173 else {
a261571f 174 Carp::carp("Only refs supported, ignoring non-ref item \$$k");
3bd791fa 175 }
823edd99
GS
176 }
177 else {
a261571f 178 Carp::carp("Value of ref must be defined; ignoring undefined item \$$k");
823edd99
GS
179 }
180 }
181 return $s;
182 }
183 else {
184 return map { @$_ } values %{$s->{seen}};
185 }
186}
187
188#
189# set or query the values to be dumped
190#
191sub Values {
192 my($s, $v) = @_;
3bd791fa
JK
193 if (defined($v)) {
194 if (ref($v) eq 'ARRAY') {
195 $s->{todump} = [@$v]; # make a copy
196 return $s;
197 }
198 else {
a261571f 199 Carp::croak("Argument to Values, if provided, must be array ref");
3bd791fa 200 }
823edd99
GS
201 }
202 else {
203 return @{$s->{todump}};
204 }
205}
206
207#
208# set or query the names of the values to be dumped
209#
210sub Names {
211 my($s, $n) = @_;
3bd791fa
JK
212 if (defined($n)) {
213 if (ref($n) eq 'ARRAY') {
214 $s->{names} = [@$n]; # make a copy
215 return $s;
216 }
217 else {
a261571f 218 Carp::croak("Argument to Names, if provided, must be array ref");
3bd791fa 219 }
823edd99
GS
220 }
221 else {
222 return @{$s->{names}};
223 }
224}
225
226sub DESTROY {}
227
0f1923bd 228sub Dump {
e1416070
S
229 # On old versions of perl, the xs-deparse support can fail
230 # mysteriously. Barring copious spare time, it's best to revert
231 # to the previously standard behavior of using the pure perl dumper
232 # for deparsing on old perls. --Steffen
233 if (IS_PRE_520_PERL and ($Data::Dumper::Deparse or (ref($_[0]) && $_[0]->{deparse}))) {
234 return &Dumpperl;
235 }
31ac59b6 236
e1416070
S
237 return &Dumpxs
238 unless $Data::Dumper::Useperl || (ref($_[0]) && $_[0]->{useperl})
31ac59b6
KW
239 # Use pure perl version on earlier releases on EBCDIC platforms
240 || (! $IS_ASCII && $] lt 5.021_010);
e1416070 241 return &Dumpperl;
0f1923bd
GS
242}
243
823edd99
GS
244#
245# dump the refs in the current dumper object.
246# expects same args as new() if called via package name.
247#
0f1923bd 248sub Dumpperl {
823edd99
GS
249 my($s) = shift;
250 my(@out, $val, $name);
251 my($i) = 0;
252 local(@post);
2728842d 253 init_refaddr_format();
823edd99
GS
254
255 $s = $s->new(@_) unless ref $s;
256
257 for $val (@{$s->{todump}}) {
823edd99
GS
258 @post = ();
259 $name = $s->{names}[$i++];
3bd791fa 260 $name = $s->_refine_name($name, $val, $i);
823edd99
GS
261
262 my $valstr;
263 {
264 local($s->{apad}) = $s->{apad};
d34e9bd9 265 $s->{apad} .= ' ' x (length($name) + 3) if $s->{indent} >= 2 and !$s->{terse};
823edd99
GS
266 $valstr = $s->_dump($val, $name);
267 }
268
269 $valstr = "$name = " . $valstr . ';' if @post or !$s->{terse};
3bd791fa 270 my $out = $s->_compose_out($valstr, \@post);
823edd99
GS
271
272 push @out, $out;
273 }
274 return wantarray ? @out : join('', @out);
275}
276
d0c214fd
AF
277# wrap string in single quotes (escaping if needed)
278sub _quote {
279 my $val = shift;
280 $val =~ s/([\\\'])/\\$1/g;
281 return "'" . $val . "'";
282}
283
d036e907
FC
284# Old Perls (5.14-) have trouble resetting vstring magic when it is no
285# longer valid.
286use constant _bad_vsmg => defined &_vstring && (_vstring(~v0)||'') eq "v0";
287
823edd99
GS
288#
289# twist, toil and turn;
290# and recurse, of course.
31a725b3
JH
291# sometimes sordidly;
292# and curse if no recourse.
823edd99
GS
293#
294sub _dump {
295 my($s, $val, $name) = @_;
3bd791fa 296 my($out, $type, $id, $sname);
823edd99 297
823edd99
GS
298 $type = ref $val;
299 $out = "";
300
301 if ($type) {
302
c5f7c514
ST
303 # Call the freezer method if it's specified and the object has the
304 # method. Trap errors and warn() instead of die()ing, like the XS
305 # implementation.
306 my $freezer = $s->{freezer};
307 if ($freezer and UNIVERSAL::can($val, $freezer)) {
308 eval { $val->$freezer() };
309 warn "WARNING(Freezer method call failed): $@" if $@;
823edd99
GS
310 }
311
2728842d 312 require Scalar::Util;
3bd791fa
JK
313 my $realpack = Scalar::Util::blessed($val);
314 my $realtype = $realpack ? Scalar::Util::reftype($val) : ref $val;
2728842d 315 $id = format_refaddr($val);
a2126434 316
3bd791fa 317 # Note: By this point $name is always defined and of non-zero length.
436d4ccf 318 # Keep a tab on it so that we do not fall into recursive pit.
3bd791fa
JK
319 if (exists $s->{seen}{$id}) {
320 if ($s->{purity} and $s->{level} > 0) {
321 $out = ($realtype eq 'HASH') ? '{}' :
322 ($realtype eq 'ARRAY') ? '[]' :
323 'do{my $o}' ;
324 push @post, $name . " = " . $s->{seen}{$id}[0];
7820172a
GS
325 }
326 else {
3bd791fa
JK
327 $out = $s->{seen}{$id}[0];
328 if ($name =~ /^([\@\%])/) {
329 my $start = $1;
330 if ($out =~ /^\\$start/) {
331 $out = substr($out, 1);
332 }
333 else {
334 $out = $start . '{' . $out . '}';
335 }
336 }
823edd99 337 }
3bd791fa
JK
338 return $out;
339 }
340 else {
341 # store our name
342 $s->{seen}{$id} = [ (
343 ($name =~ /^[@%]/)
344 ? ('\\' . $name )
345 : ($realtype eq 'CODE' and $name =~ /^[*](.*)$/)
346 ? ('\\&' . $1 )
347 : $name
348 ), $val ];
823edd99 349 }
3bd791fa 350 my $no_bless = 0;
4ab99479
YO
351 my $is_regex = 0;
352 if ( $realpack and ($] >= 5.009005 ? re::is_regexp($val) : $realpack eq 'Regexp') ) {
353 $is_regex = 1;
354 $no_bless = $realpack eq 'Regexp';
a2126434
JN
355 }
356
3bd791fa 357 # If purity is not set and maxdepth is set, then check depth:
a2126434
JN
358 # if we have reached maximum depth, return the string
359 # representation of the thing we are currently examining
3bd791fa 360 # at this depth (i.e., 'Foo=ARRAY(0xdeadbeef)').
a2126434 361 if (!$s->{purity}
3bd791fa
JK
362 and defined($s->{maxdepth})
363 and $s->{maxdepth} > 0
364 and $s->{level} >= $s->{maxdepth})
a2126434
JN
365 {
366 return qq['$val'];
367 }
368
19be3be6
TC
369 # avoid recursing infinitely [perl #122111]
370 if ($s->{maxrecurse} > 0
371 and $s->{level} >= $s->{maxrecurse}) {
372 die "Recursion limit of $s->{maxrecurse} exceeded";
373 }
374
a2126434 375 # we have a blessed ref
3bd791fa 376 my ($blesspad);
4ab99479 377 if ($realpack and !$no_bless) {
a2126434
JN
378 $out = $s->{'bless'} . '( ';
379 $blesspad = $s->{apad};
380 $s->{apad} .= ' ' if ($s->{indent} >= 2);
7894fbab
GS
381 }
382
823edd99 383 $s->{level}++;
3bd791fa 384 my $ipad = $s->{xpad} x $s->{level};
823edd99 385
4ab99479
YO
386 if ($is_regex) {
387 my $pat;
b183d514
TC
388 my $flags = "";
389 if (defined(*re::regexp_pattern{CODE})) {
390 ($pat, $flags) = re::regexp_pattern($val);
3bd791fa
JK
391 }
392 else {
393 $pat = "$val";
4ab99479 394 }
de5ef703 395 $pat =~ s <(\\.)|/> { $1 || '\\/' }ge;
b183d514 396 $out .= "qr/$pat/$flags";
4ab99479 397 }
d036e907 398 elsif ($realtype eq 'SCALAR' || $realtype eq 'REF'
3bd791fa 399 || $realtype eq 'VSTRING') {
823edd99 400 if ($realpack) {
3bd791fa 401 $out .= 'do{\\(my $o = ' . $s->_dump($$val, "\${$name}") . ')}';
823edd99
GS
402 }
403 else {
3bd791fa 404 $out .= '\\' . $s->_dump($$val, "\${$name}");
823edd99
GS
405 }
406 }
407 elsif ($realtype eq 'GLOB') {
3bd791fa 408 $out .= '\\' . $s->_dump($$val, "*{$name}");
823edd99
GS
409 }
410 elsif ($realtype eq 'ARRAY') {
a36ee16f 411 my($pad, $mname);
823edd99
GS
412 my($i) = 0;
413 $out .= ($name =~ /^\@/) ? '(' : '[';
414 $pad = $s->{sep} . $s->{pad} . $s->{apad};
3bd791fa
JK
415 ($name =~ /^\@(.*)$/) ? ($mname = "\$" . $1) :
416 # omit -> if $foo->[0]->{bar}, but not ${$foo->[0]}->{bar}
417 ($name =~ /^\\?[\%\@\*\$][^{].*[]}]$/) ? ($mname = $name) :
418 ($mname = $name . '->');
823edd99 419 $mname .= '->' if $mname =~ /^\*.+\{[A-Z]+\}$/;
a36ee16f 420 for my $v (@$val) {
3bd791fa
JK
421 $sname = $mname . '[' . $i . ']';
422 $out .= $pad . $ipad . '#' . $i
423 if $s->{indent} >= 3;
424 $out .= $pad . $ipad . $s->_dump($v, $sname);
7089d392
AC
425 $out .= ","
426 if $i++ < $#$val
427 || ($s->{trailingcomma} && $s->{indent} >= 1);
823edd99
GS
428 }
429 $out .= $pad . ($s->{xpad} x ($s->{level} - 1)) if $i;
430 $out .= ($name =~ /^\@/) ? ')' : ']';
431 }
432 elsif ($realtype eq 'HASH') {
3bd791fa 433 my ($k, $v, $pad, $lpad, $mname, $pair);
823edd99
GS
434 $out .= ($name =~ /^\%/) ? '(' : '{';
435 $pad = $s->{sep} . $s->{pad} . $s->{apad};
436 $lpad = $s->{apad};
30b4f386 437 $pair = $s->{pair};
7820172a 438 ($name =~ /^\%(.*)$/) ? ($mname = "\$" . $1) :
3bd791fa
JK
439 # omit -> if $foo->[0]->{bar}, but not ${$foo->[0]}->{bar}
440 ($name =~ /^\\?[\%\@\*\$][^{].*[]}]$/) ? ($mname = $name) :
441 ($mname = $name . '->');
823edd99 442 $mname .= '->' if $mname =~ /^\*.+\{[A-Z]+\}$/;
3bd791fa
JK
443 my $sortkeys = defined($s->{sortkeys}) ? $s->{sortkeys} : '';
444 my $keys = [];
31a725b3 445 if ($sortkeys) {
3bd791fa
JK
446 if (ref($s->{sortkeys}) eq 'CODE') {
447 $keys = $s->{sortkeys}($val);
448 unless (ref($keys) eq 'ARRAY') {
a261571f 449 Carp::carp("Sortkeys subroutine did not return ARRAYREF");
3bd791fa
JK
450 $keys = [];
451 }
452 }
453 else {
454 $keys = [ sort keys %$val ];
455 }
31a725b3 456 }
b36d99fa
AV
457
458 # Ensure hash iterator is reset
459 keys(%$val);
460
3bd791fa 461 my $key;
31a725b3 462 while (($k, $v) = ! $sortkeys ? (each %$val) :
3bd791fa
JK
463 @$keys ? ($key = shift(@$keys), $val->{$key}) :
464 () )
31a725b3 465 {
3bd791fa 466 my $nk = $s->_dump($k, "");
5b50ddc0
TC
467
468 # _dump doesn't quote numbers of this form
469 if ($s->{quotekeys} && $nk =~ /^(?:0|-?[1-9][0-9]{0,8})\z/) {
470 $nk = $s->{useqq} ? qq("$nk") : qq('$nk');
471 }
472 elsif (!$s->{quotekeys} and $nk =~ /^[\"\']([A-Za-z_]\w*)[\"\']$/) {
473 $nk = $1
474 }
475
3bd791fa
JK
476 $sname = $mname . '{' . $nk . '}';
477 $out .= $pad . $ipad . $nk . $pair;
478
479 # temporarily alter apad
480 $s->{apad} .= (" " x (length($nk) + 4))
481 if $s->{indent} >= 2;
482 $out .= $s->_dump($val->{$k}, $sname) . ",";
483 $s->{apad} = $lpad
484 if $s->{indent} >= 2;
823edd99
GS
485 }
486 if (substr($out, -1) eq ',') {
7089d392 487 chop $out if !$s->{trailingcomma} || !$s->{indent};
3bd791fa 488 $out .= $pad . ($s->{xpad} x ($s->{level} - 1));
823edd99
GS
489 }
490 $out .= ($name =~ /^\%/) ? ')' : '}';
491 }
492 elsif ($realtype eq 'CODE') {
8e5f9a6e 493 if ($s->{deparse}) {
3bd791fa
JK
494 require B::Deparse;
495 my $sub = 'sub ' . (B::Deparse->new)->coderef2text($val);
496 $pad = $s->{sep} . $s->{pad} . $s->{apad} . $s->{xpad} x ($s->{level} - 1);
942cf643 497 $sub =~ s/\n/$pad/gs;
3bd791fa
JK
498 $out .= $sub;
499 }
500 else {
8e5f9a6e 501 $out .= 'sub { "DUMMY" }';
a261571f 502 Carp::carp("Encountered CODE ref, using dummy placeholder") if $s->{purity};
8e5f9a6e 503 }
823edd99
GS
504 }
505 else {
a261571f 506 Carp::croak("Can't handle '$realtype' type");
823edd99 507 }
3bd791fa 508
4ab99479 509 if ($realpack and !$no_bless) { # we have a blessed ref
d0c214fd 510 $out .= ', ' . _quote($realpack) . ' )';
3bd791fa
JK
511 $out .= '->' . $s->{toaster} . '()'
512 if $s->{toaster} ne '';
823edd99
GS
513 $s->{apad} = $blesspad;
514 }
515 $s->{level}--;
823edd99
GS
516 }
517 else { # simple scalar
518
519 my $ref = \$_[1];
d036e907 520 my $v;
823edd99
GS
521 # first, catalog the scalar
522 if ($name ne '') {
2728842d 523 $id = format_refaddr($ref);
823edd99 524 if (exists $s->{seen}{$id}) {
7820172a 525 if ($s->{seen}{$id}[2]) {
3bd791fa
JK
526 $out = $s->{seen}{$id}[0];
527 #warn "[<$out]\n";
528 return "\${$out}";
529 }
823edd99
GS
530 }
531 else {
3bd791fa
JK
532 #warn "[>\\$name]\n";
533 $s->{seen}{$id} = ["\\$name", $ref];
823edd99
GS
534 }
535 }
c1205a1e
FC
536 $ref = \$val;
537 if (ref($ref) eq 'GLOB') { # glob
823edd99 538 my $name = substr($val, 1);
abda9fe0
Z
539 $name =~ s/^main::(?!\z)/::/;
540 if ($name =~ /\A(?:[A-Z_a-z][0-9A-Z_a-z]*)?::(?:[0-9A-Z_a-z]+::)*[0-9A-Z_a-z]*\z/ && $name ne 'main::') {
3bd791fa 541 $sname = $name;
823edd99
GS
542 }
543 else {
3bd791fa
JK
544 $sname = $s->_dump(
545 $name eq 'main::' || $] < 5.007 && $name eq "main::\0"
546 ? ''
547 : $name,
548 "",
549 );
550 $sname = '{' . $sname . '}';
823edd99
GS
551 }
552 if ($s->{purity}) {
3bd791fa
JK
553 my $k;
554 local ($s->{level}) = 0;
555 for $k (qw(SCALAR ARRAY HASH)) {
556 my $gval = *$val{$k};
557 next unless defined $gval;
558 next if $k eq "SCALAR" && ! defined $$gval; # always there
559
560 # _dump can push into @post, so we hold our place using $postlen
561 my $postlen = scalar @post;
562 $post[$postlen] = "\*$sname = ";
563 local ($s->{apad}) = " " x length($post[$postlen]) if $s->{indent} >= 2;
564 $post[$postlen] .= $s->_dump($gval, "\*$sname\{$k\}");
565 }
823edd99
GS
566 }
567 $out .= '*' . $sname;
568 }
7820172a
GS
569 elsif (!defined($val)) {
570 $out .= "undef";
571 }
d036e907 572 elsif (defined &_vstring and $v = _vstring($val)
3bd791fa 573 and !_bad_vsmg || eval $v eq $val) {
d036e907
FC
574 $out .= $v;
575 }
576 elsif (!defined &_vstring
c1205a1e 577 and ref $ref eq 'VSTRING' || eval{Scalar::Util::isvstring($val)}) {
d036e907
FC
578 $out .= sprintf "%vd", $val;
579 }
5b50ddc0
TC
580 # \d here would treat "1\x{660}" as a safe decimal number
581 elsif ($val =~ /^(?:0|-?[1-9][0-9]{0,8})\z/) { # safe decimal number
823edd99
GS
582 $out .= $val;
583 }
3bd791fa 584 else { # string
c4cce848 585 if ($s->{useqq} or $val =~ tr/\0-\377//c) {
38a44b82 586 # Fall back to qq if there's Unicode
3bd791fa 587 $out .= qquote($val, $s->{useqq});
823edd99
GS
588 }
589 else {
d0c214fd 590 $out .= _quote($val);
823edd99
GS
591 }
592 }
593 }
7820172a
GS
594 if ($id) {
595 # if we made it this far, $id was added to seen list at current
596 # level, so remove it to get deep copies
597 if ($s->{deepcopy}) {
598 delete($s->{seen}{$id});
599 }
600 elsif ($name) {
601 $s->{seen}{$id}[2] = 1;
602 }
603 }
823edd99
GS
604 return $out;
605}
3bd791fa 606
823edd99
GS
607#
608# non-OO style of earlier version
609#
610sub Dumper {
611 return Data::Dumper->Dump([@_]);
612}
613
0f1923bd 614# compat stub
823edd99
GS
615sub DumperX {
616 return Data::Dumper->Dumpxs([@_], []);
617}
618
823edd99 619#
3bd791fa 620# reset the "seen" cache
823edd99
GS
621#
622sub Reset {
623 my($s) = shift;
624 $s->{seen} = {};
625 return $s;
626}
627
628sub Indent {
629 my($s, $v) = @_;
dd9e86b4 630 if (@_ >= 2) {
823edd99
GS
631 if ($v == 0) {
632 $s->{xpad} = "";
633 $s->{sep} = "";
634 }
635 else {
636 $s->{xpad} = " ";
637 $s->{sep} = "\n";
638 }
639 $s->{indent} = $v;
640 return $s;
641 }
642 else {
643 return $s->{indent};
644 }
645}
646
7089d392
AC
647sub Trailingcomma {
648 my($s, $v) = @_;
dd9e86b4 649 @_ >= 2 ? (($s->{trailingcomma} = $v), return $s) : $s->{trailingcomma};
7089d392
AC
650}
651
30b4f386 652sub Pair {
653 my($s, $v) = @_;
dd9e86b4 654 @_ >= 2 ? (($s->{pair} = $v), return $s) : $s->{pair};
30b4f386 655}
656
823edd99
GS
657sub Pad {
658 my($s, $v) = @_;
dd9e86b4 659 @_ >= 2 ? (($s->{pad} = $v), return $s) : $s->{pad};
823edd99
GS
660}
661
662sub Varname {
663 my($s, $v) = @_;
dd9e86b4 664 @_ >= 2 ? (($s->{varname} = $v), return $s) : $s->{varname};
823edd99
GS
665}
666
667sub Purity {
668 my($s, $v) = @_;
dd9e86b4 669 @_ >= 2 ? (($s->{purity} = $v), return $s) : $s->{purity};
823edd99
GS
670}
671
672sub Useqq {
673 my($s, $v) = @_;
dd9e86b4 674 @_ >= 2 ? (($s->{useqq} = $v), return $s) : $s->{useqq};
823edd99
GS
675}
676
677sub Terse {
678 my($s, $v) = @_;
dd9e86b4 679 @_ >= 2 ? (($s->{terse} = $v), return $s) : $s->{terse};
823edd99
GS
680}
681
682sub Freezer {
683 my($s, $v) = @_;
dd9e86b4 684 @_ >= 2 ? (($s->{freezer} = $v), return $s) : $s->{freezer};
823edd99
GS
685}
686
687sub Toaster {
688 my($s, $v) = @_;
dd9e86b4 689 @_ >= 2 ? (($s->{toaster} = $v), return $s) : $s->{toaster};
823edd99
GS
690}
691
692sub Deepcopy {
693 my($s, $v) = @_;
dd9e86b4 694 @_ >= 2 ? (($s->{deepcopy} = $v), return $s) : $s->{deepcopy};
823edd99
GS
695}
696
697sub Quotekeys {
698 my($s, $v) = @_;
dd9e86b4 699 @_ >= 2 ? (($s->{quotekeys} = $v), return $s) : $s->{quotekeys};
823edd99
GS
700}
701
702sub Bless {
703 my($s, $v) = @_;
dd9e86b4 704 @_ >= 2 ? (($s->{'bless'} = $v), return $s) : $s->{'bless'};
823edd99
GS
705}
706
a2126434
JN
707sub Maxdepth {
708 my($s, $v) = @_;
dd9e86b4 709 @_ >= 2 ? (($s->{'maxdepth'} = $v), return $s) : $s->{'maxdepth'};
a2126434
JN
710}
711
19be3be6
TC
712sub Maxrecurse {
713 my($s, $v) = @_;
dd9e86b4 714 @_ >= 2 ? (($s->{'maxrecurse'} = $v), return $s) : $s->{'maxrecurse'};
19be3be6
TC
715}
716
31a725b3
JH
717sub Useperl {
718 my($s, $v) = @_;
dd9e86b4 719 @_ >= 2 ? (($s->{'useperl'} = $v), return $s) : $s->{'useperl'};
31a725b3
JH
720}
721
722sub Sortkeys {
723 my($s, $v) = @_;
dd9e86b4 724 @_ >= 2 ? (($s->{'sortkeys'} = $v), return $s) : $s->{'sortkeys'};
31a725b3
JH
725}
726
8e5f9a6e
RGS
727sub Deparse {
728 my($s, $v) = @_;
dd9e86b4 729 @_ >= 2 ? (($s->{'deparse'} = $v), return $s) : $s->{'deparse'};
8e5f9a6e 730}
a2126434 731
d424882c
S
732sub Sparseseen {
733 my($s, $v) = @_;
dd9e86b4 734 @_ >= 2 ? (($s->{'noseen'} = $v), return $s) : $s->{'noseen'};
d424882c
S
735}
736
7820172a 737# used by qquote below
3bd791fa 738my %esc = (
7820172a
GS
739 "\a" => "\\a",
740 "\b" => "\\b",
741 "\t" => "\\t",
742 "\n" => "\\n",
743 "\f" => "\\f",
744 "\r" => "\\r",
745 "\e" => "\\e",
746);
747
31ac59b6
KW
748my $low_controls = ($IS_ASCII)
749
750 # This includes \177, because traditionally it has been
751 # output as octal, even though it isn't really a "low"
752 # control
753 ? qr/[\0-\x1f\177]/
754
755 # EBCDIC low controls.
756 : qr/[\0-\x3f]/;
757
823edd99
GS
758# put a string value in double quotes
759sub qquote {
760 local($_) = shift;
7820172a 761 s/([\\\"\@\$])/\\$1/g;
31ac59b6
KW
762
763 # This efficiently changes the high ordinal characters to \x{} if the utf8
764 # flag is on. On ASCII platforms, the high ordinals are all the
765 # non-ASCII's. On EBCDIC platforms, we don't include in these the non-ASCII
766 # controls whose ordinals are less than SPACE, excluded below by the range
767 # \0-\x3f. On ASCII platforms this range just compiles as part of :ascii:.
768 # On EBCDIC platforms, there is just one outlier high ordinal control, and
769 # it gets output as \x{}.
dc71dc59 770 my $bytes; { use bytes; $bytes = length }
31ac59b6
KW
771 s/([^[:ascii:]\0-\x3f])/sprintf("\\x{%x}",ord($1))/ge
772 if $bytes > length
7820172a 773
31ac59b6
KW
774 # The above doesn't get the EBCDIC outlier high ordinal control when
775 # the string is UTF-8 but there are no UTF-8 variant characters in it.
776 # We want that to come out as \x{} anyway. We need is_utf8() to do
777 # this.
778 || (! $IS_ASCII && $] ge 5.008_001 && utf8::is_utf8($_));
779
b8cae652 780 return qq("$_") unless /[[:^print:]]/; # fast exit if only printables
31ac59b6
KW
781
782 # Here, there is at least one non-printable to output. First, translate the
783 # escapes.
7820172a
GS
784 s/([\a\b\t\n\f\r\e])/$esc{$1}/g;
785
31ac59b6
KW
786 # no need for 3 digits in escape for octals not followed by a digit.
787 s/($low_controls)(?!\d)/'\\'.sprintf('%o',ord($1))/eg;
788
789 # But otherwise use 3 digits
790 s/($low_controls)/'\\'.sprintf('%03o',ord($1))/eg;
791
43948175 792 # all but last branch below not supported --BEHAVIOR SUBJECT TO CHANGE--
31ac59b6
KW
793 my $high = shift || "";
794 if ($high eq "iso8859") { # Doesn't escape the Latin1 printables
795 if ($IS_ASCII) {
796 s/([\200-\240])/'\\'.sprintf('%o',ord($1))/eg;
797 }
798 elsif ($] ge 5.007_003) {
799 my $high_control = utf8::unicode_to_native(0x9F);
800 s/$high_control/sprintf('\\%o',ord($1))/eg;
801 }
0407a77b 802 } elsif ($high eq "utf8") {
31ac59b6
KW
803# Some discussion of what to do here is in
804# https://rt.perl.org/Ticket/Display.html?id=113088
0407a77b
GS
805# use utf8;
806# $str =~ s/([^\040-\176])/sprintf "\\x{%04x}", ord($1)/ge;
807 } elsif ($high eq "8bit") {
808 # leave it as it is
809 } else {
31ac59b6
KW
810 s/([[:^ascii:]])/'\\'.sprintf('%03o',ord($1))/eg;
811 #s/([^\040-\176])/sprintf "\\x{%04x}", ord($1)/ge;
0407a77b 812 }
0407a77b 813
7820172a 814 return qq("$_");
823edd99
GS
815}
816
fec5e1eb
IM
817# helper sub to sort hash keys in Perl < 5.8.0 where we don't have
818# access to sortsv() from XS
819sub _sortkeys { [ sort keys %{$_[0]} ] }
820
3bd791fa
JK
821sub _refine_name {
822 my $s = shift;
823 my ($name, $val, $i) = @_;
824 if (defined $name) {
825 if ($name =~ /^[*](.*)$/) {
826 if (defined $val) {
827 $name = (ref $val eq 'ARRAY') ? ( "\@" . $1 ) :
828 (ref $val eq 'HASH') ? ( "\%" . $1 ) :
829 (ref $val eq 'CODE') ? ( "\*" . $1 ) :
830 ( "\$" . $1 ) ;
831 }
832 else {
833 $name = "\$" . $1;
834 }
835 }
836 elsif ($name !~ /^\$/) {
837 $name = "\$" . $name;
838 }
839 }
840 else { # no names provided
841 $name = "\$" . $s->{varname} . $i;
842 }
843 return $name;
844}
845
846sub _compose_out {
847 my $s = shift;
848 my ($valstr, $postref) = @_;
849 my $out = "";
850 $out .= $s->{pad} . $valstr . $s->{sep};
851 if (@{$postref}) {
852 $out .= $s->{pad} .
853 join(';' . $s->{sep} . $s->{pad}, @{$postref}) .
854 ';' .
855 $s->{sep};
856 }
857 return $out;
858}
859
823edd99
GS
8601;
861__END__
862
863=head1 NAME
864
865Data::Dumper - stringified perl data structures, suitable for both printing and C<eval>
866
823edd99
GS
867=head1 SYNOPSIS
868
869 use Data::Dumper;
870
871 # simple procedural interface
872 print Dumper($foo, $bar);
873
874 # extended usage with names
875 print Data::Dumper->Dump([$foo, $bar], [qw(foo *ary)]);
876
877 # configuration variables
878 {
82df27e1 879 local $Data::Dumper::Purity = 1;
823edd99
GS
880 eval Data::Dumper->Dump([$foo, $bar], [qw(foo *ary)]);
881 }
882
883 # OO usage
884 $d = Data::Dumper->new([$foo, $bar], [qw(foo *ary)]);
885 ...
886 print $d->Dump;
887 ...
888 $d->Purity(1)->Terse(1)->Deepcopy(1);
889 eval $d->Dump;
890
891
892=head1 DESCRIPTION
893
894Given a list of scalars or reference variables, writes out their contents in
5e603302 895perl syntax. The references can also be objects. The content of each
823edd99
GS
896variable is output in a single Perl statement. Handles self-referential
897structures correctly.
898
899The return value can be C<eval>ed to get back an identical copy of the
d22722a1
S
900original reference structure. (Please do consider the security implications
901of eval'ing code from untrusted sources!)
823edd99
GS
902
903Any references that are the same as one of those passed in will be named
904C<$VAR>I<n> (where I<n> is a numeric suffix), and other duplicate references
905to substructures within C<$VAR>I<n> will be appropriately labeled using arrow
906notation. You can specify names for individual values to be dumped if you
907use the C<Dump()> method, or you can change the default C<$VAR> prefix to
908something else. See C<$Data::Dumper::Varname> and C<$Data::Dumper::Terse>
909below.
910
911The default output of self-referential structures can be C<eval>ed, but the
912nested references to C<$VAR>I<n> will be undefined, since a recursive
913structure cannot be constructed using one Perl statement. You should set the
914C<Purity> flag to 1 to get additional statements that will correctly fill in
fc3a748c
RGS
915these references. Moreover, if C<eval>ed when strictures are in effect,
916you need to ensure that any variables it accesses are previously declared.
823edd99
GS
917
918In the extended usage form, the references to be dumped can be given
3bd791fa 919user-specified names. If a name begins with a C<*>, the output will
823edd99
GS
920describe the dereferenced type of the supplied reference for hashes and
921arrays, and coderefs. Output of names will be avoided where possible if
922the C<Terse> flag is set.
923
924In many cases, methods that are used to set the internal state of the
925object will return the object itself, so method calls can be conveniently
926chained together.
927
928Several styles of output are possible, all controlled by setting
3bd791fa 929the C<Indent> flag. See L<Configuration Variables or Methods> below
823edd99
GS
930for details.
931
932
933=head2 Methods
934
935=over 4
936
937=item I<PACKAGE>->new(I<ARRAYREF [>, I<ARRAYREF]>)
938
939Returns a newly created C<Data::Dumper> object. The first argument is an
940anonymous array of values to be dumped. The optional second argument is an
941anonymous array of names for the values. The names need not have a leading
942C<$> sign, and must be comprised of alphanumeric characters. You can begin
943a name with a C<*> to specify that the dereferenced type must be dumped
944instead of the reference itself, for ARRAY and HASH references.
945
946The prefix specified by C<$Data::Dumper::Varname> will be used with a
947numeric suffix if the name for a value is undefined.
948
949Data::Dumper will catalog all references encountered while dumping the
950values. Cross-references (in the form of names of substructures in perl
951syntax) will be inserted at all possible points, preserving any structural
952interdependencies in the original set of values. Structure traversal is
953depth-first, and proceeds in order from the first supplied value to
954the last.
955
956=item I<$OBJ>->Dump I<or> I<PACKAGE>->Dump(I<ARRAYREF [>, I<ARRAYREF]>)
957
958Returns the stringified form of the values stored in the object (preserving
959the order in which they were supplied to C<new>), subject to the
91e74348 960configuration options below. In a list context, it returns a list
823edd99
GS
961of strings corresponding to the supplied values.
962
963The second form, for convenience, simply calls the C<new> method on its
964arguments before dumping the object immediately.
965
823edd99
GS
966=item I<$OBJ>->Seen(I<[HASHREF]>)
967
968Queries or adds to the internal table of already encountered references.
969You must use C<Reset> to explicitly clear the table if needed. Such
970references are not dumped; instead, their names are inserted wherever they
971are encountered subsequently. This is useful especially for properly
972dumping subroutine references.
973
d1be9408 974Expects an anonymous hash of name => value pairs. Same rules apply for names
823edd99 975as in C<new>. If no argument is supplied, will return the "seen" list of
91e74348 976name => value pairs, in a list context. Otherwise, returns the object
823edd99
GS
977itself.
978
979=item I<$OBJ>->Values(I<[ARRAYREF]>)
980
3bd791fa
JK
981Queries or replaces the internal array of values that will be dumped. When
982called without arguments, returns the values as a list. When called with a
983reference to an array of replacement values, returns the object itself. When
984called with any other type of argument, dies.
823edd99
GS
985
986=item I<$OBJ>->Names(I<[ARRAYREF]>)
987
988Queries or replaces the internal array of user supplied names for the values
3bd791fa
JK
989that will be dumped. When called without arguments, returns the names. When
990called with an array of replacement names, returns the object itself. If the
436d4ccf 991number of replacement names exceeds the number of values to be named, the
3bd791fa 992excess names will not be used. If the number of replacement names falls short
436d4ccf 993of the number of values to be named, the list of replacement names will be
3bd791fa
JK
994exhausted and remaining values will not be renamed. When
995called with any other type of argument, dies.
823edd99
GS
996
997=item I<$OBJ>->Reset
998
999Clears the internal table of "seen" references and returns the object
1000itself.
1001
1002=back
1003
1004=head2 Functions
1005
1006=over 4
1007
1008=item Dumper(I<LIST>)
1009
1010Returns the stringified form of the values in the list, subject to the
1011configuration options below. The values will be named C<$VAR>I<n> in the
1012output, where I<n> is a numeric suffix. Will return a list of strings
91e74348 1013in a list context.
823edd99 1014
823edd99
GS
1015=back
1016
1017=head2 Configuration Variables or Methods
1018
1019Several configuration variables can be used to control the kind of output
1020generated when using the procedural interface. These variables are usually
1021C<local>ized in a block so that other parts of the code are not affected by
3bd791fa 1022the change.
823edd99
GS
1023
1024These variables determine the default state of the object created by calling
1025the C<new> method, but cannot be used to alter the state of the object
1026thereafter. The equivalent method names should be used instead to query
1027or set the internal state of the object.
1028
1029The method forms return the object itself when called with arguments,
1030so that they can be chained together nicely.
1031
1032=over 4
1033
28bf64cc
JH
1034=item *
1035
1036$Data::Dumper::Indent I<or> I<$OBJ>->Indent(I<[NEWVAL]>)
823edd99
GS
1037
1038Controls the style of indentation. It can be set to 0, 1, 2 or 3. Style 0
1039spews output without any newlines, indentation, or spaces between list
1040items. It is the most compact format possible that can still be called
1041valid perl. Style 1 outputs a readable form with newlines but no fancy
1042indentation (each level in the structure is simply indented by a fixed
1043amount of whitespace). Style 2 (the default) outputs a very readable form
1044which takes into account the length of hash keys (so the hash value lines
1045up). Style 3 is like style 2, but also annotates the elements of arrays
1046with their index (but the comment is on its own line, so array output
1047consumes twice the number of lines). Style 2 is the default.
1048
28bf64cc
JH
1049=item *
1050
7089d392
AC
1051$Data::Dumper::Trailingcomma I<or> I<$OBJ>->Trailingcomma(I<[NEWVAL]>)
1052
1053Controls whether a comma is added after the last element of an array or
1054hash. Even when true, no comma is added between the last element of an array
1055or hash and a closing bracket when they appear on the same line. The default
1056is false.
1057
1058=item *
1059
28bf64cc 1060$Data::Dumper::Purity I<or> I<$OBJ>->Purity(I<[NEWVAL]>)
823edd99
GS
1061
1062Controls the degree to which the output can be C<eval>ed to recreate the
1063supplied reference structures. Setting it to 1 will output additional perl
1064statements that will correctly recreate nested references. The default is
10650.
1066
28bf64cc
JH
1067=item *
1068
1069$Data::Dumper::Pad I<or> I<$OBJ>->Pad(I<[NEWVAL]>)
823edd99
GS
1070
1071Specifies the string that will be prefixed to every line of the output.
1072Empty string by default.
1073
28bf64cc
JH
1074=item *
1075
1076$Data::Dumper::Varname I<or> I<$OBJ>->Varname(I<[NEWVAL]>)
823edd99
GS
1077
1078Contains the prefix to use for tagging variable names in the output. The
1079default is "VAR".
1080
28bf64cc
JH
1081=item *
1082
1083$Data::Dumper::Useqq I<or> I<$OBJ>->Useqq(I<[NEWVAL]>)
823edd99
GS
1084
1085When set, enables the use of double quotes for representing string values.
1086Whitespace other than space will be represented as C<[\n\t\r]>, "unsafe"
1087characters will be backslashed, and unprintable characters will be output as
aef2570a 1088quoted octal integers. The default is 0.
823edd99 1089
28bf64cc
JH
1090=item *
1091
1092$Data::Dumper::Terse I<or> I<$OBJ>->Terse(I<[NEWVAL]>)
823edd99
GS
1093
1094When set, Data::Dumper will emit single, non-self-referential values as
1095atoms/terms rather than statements. This means that the C<$VAR>I<n> names
1096will be avoided where possible, but be advised that such output may not
1097always be parseable by C<eval>.
1098
28bf64cc
JH
1099=item *
1100
1101$Data::Dumper::Freezer I<or> $I<OBJ>->Freezer(I<[NEWVAL]>)
823edd99
GS
1102
1103Can be set to a method name, or to an empty string to disable the feature.
1104Data::Dumper will invoke that method via the object before attempting to
1105stringify it. This method can alter the contents of the object (if, for
1106instance, it contains data allocated from C), and even rebless it in a
1107different package. The client is responsible for making sure the specified
1108method can be called via the object, and that the object ends up containing
1109only perl data types after the method has been called. Defaults to an empty
1110string.
1111
c5f7c514
ST
1112If an object does not support the method specified (determined using
1113UNIVERSAL::can()) then the call will be skipped. If the method dies a
1114warning will be generated.
1115
28bf64cc
JH
1116=item *
1117
1118$Data::Dumper::Toaster I<or> $I<OBJ>->Toaster(I<[NEWVAL]>)
823edd99
GS
1119
1120Can be set to a method name, or to an empty string to disable the feature.
1121Data::Dumper will emit a method call for any objects that are to be dumped
8e5f9a6e 1122using the syntax C<bless(DATA, CLASS)-E<gt>METHOD()>. Note that this means that
823edd99
GS
1123the method specified will have to perform any modifications required on the
1124object (like creating new state within it, and/or reblessing it in a
1125different package) and then return it. The client is responsible for making
1126sure the method can be called via the object, and that it returns a valid
1127object. Defaults to an empty string.
1128
28bf64cc
JH
1129=item *
1130
1131$Data::Dumper::Deepcopy I<or> $I<OBJ>->Deepcopy(I<[NEWVAL]>)
823edd99
GS
1132
1133Can be set to a boolean value to enable deep copies of structures.
1134Cross-referencing will then only be done when absolutely essential
1135(i.e., to break reference cycles). Default is 0.
1136
28bf64cc
JH
1137=item *
1138
1139$Data::Dumper::Quotekeys I<or> $I<OBJ>->Quotekeys(I<[NEWVAL]>)
823edd99
GS
1140
1141Can be set to a boolean value to control whether hash keys are quoted.
3bd791fa 1142A defined false value will avoid quoting hash keys when it looks like a simple
823edd99
GS
1143string. Default is 1, which will always enclose hash keys in quotes.
1144
28bf64cc
JH
1145=item *
1146
1147$Data::Dumper::Bless I<or> $I<OBJ>->Bless(I<[NEWVAL]>)
823edd99
GS
1148
1149Can be set to a string that specifies an alternative to the C<bless>
1150builtin operator used to create objects. A function with the specified
1151name should exist, and should accept the same arguments as the builtin.
1152Default is C<bless>.
1153
28bf64cc
JH
1154=item *
1155
30b4f386 1156$Data::Dumper::Pair I<or> $I<OBJ>->Pair(I<[NEWVAL]>)
1157
1158Can be set to a string that specifies the separator between hash keys
1159and values. To dump nested hash, array and scalar values to JavaScript,
1160use: C<$Data::Dumper::Pair = ' : ';>. Implementing C<bless> in JavaScript
1161is left as an exercise for the reader.
1162A function with the specified name exists, and accepts the same arguments
1163as the builtin.
1164
1165Default is: C< =E<gt> >.
1166
1167=item *
1168
28bf64cc 1169$Data::Dumper::Maxdepth I<or> $I<OBJ>->Maxdepth(I<[NEWVAL]>)
a2126434
JN
1170
1171Can be set to a positive integer that specifies the depth beyond which
5e603302 1172we don't venture into a structure. Has no effect when
a2126434 1173C<Data::Dumper::Purity> is set. (Useful in debugger when we often don't
3bd791fa
JK
1174want to see more than enough). Default is 0, which means there is
1175no maximum depth.
a2126434 1176
28bf64cc
JH
1177=item *
1178
19be3be6
TC
1179$Data::Dumper::Maxrecurse I<or> $I<OBJ>->Maxrecurse(I<[NEWVAL]>)
1180
1181Can be set to a positive integer that specifies the depth beyond which
1182recursion into a structure will throw an exception. This is intended
1183as a security measure to prevent perl running out of stack space when
1184dumping an excessively deep structure. Can be set to 0 to remove the
1185limit. Default is 1000.
1186
1187=item *
1188
28bf64cc 1189$Data::Dumper::Useperl I<or> $I<OBJ>->Useperl(I<[NEWVAL]>)
31a725b3
JH
1190
1191Can be set to a boolean value which controls whether the pure Perl
1192implementation of C<Data::Dumper> is used. The C<Data::Dumper> module is
1193a dual implementation, with almost all functionality written in both
1194pure Perl and also in XS ('C'). Since the XS version is much faster, it
1195will always be used if possible. This option lets you override the
1196default behavior, usually for testing purposes only. Default is 0, which
1197means the XS implementation will be used if possible.
1198
28bf64cc
JH
1199=item *
1200
1201$Data::Dumper::Sortkeys I<or> $I<OBJ>->Sortkeys(I<[NEWVAL]>)
31a725b3
JH
1202
1203Can be set to a boolean value to control whether hash keys are dumped in
1204sorted order. A true value will cause the keys of all hashes to be
1205dumped in Perl's default sort order. Can also be set to a subroutine
1206reference which will be called for each hash that is dumped. In this
1207case C<Data::Dumper> will call the subroutine once for each hash,
1208passing it the reference of the hash. The purpose of the subroutine is
1209to return a reference to an array of the keys that will be dumped, in
1210the order that they should be dumped. Using this feature, you can
1211control both the order of the keys, and which keys are actually used. In
1212other words, this subroutine acts as a filter by which you can exclude
1213certain keys from being dumped. Default is 0, which means that hash keys
1214are not sorted.
1215
28bf64cc
JH
1216=item *
1217
1218$Data::Dumper::Deparse I<or> $I<OBJ>->Deparse(I<[NEWVAL]>)
8e5f9a6e
RGS
1219
1220Can be set to a boolean value to control whether code references are
1221turned into perl source code. If set to a true value, C<B::Deparse>
b5048e7b
AC
1222will be used to get the source of the code reference. In older versions,
1223using this option imposed a significant performance penalty when dumping
1224parts of a data structure other than code references, but that is no
1225longer the case.
8e5f9a6e
RGS
1226
1227Caution : use this option only if you know that your coderefs will be
1228properly reconstructed by C<B::Deparse>.
1229
d424882c
S
1230=item *
1231
1232$Data::Dumper::Sparseseen I<or> $I<OBJ>->Sparseseen(I<[NEWVAL]>)
1233
1234By default, Data::Dumper builds up the "seen" hash of scalars that
1235it has encountered during serialization. This is very expensive.
1236This seen hash is necessary to support and even just detect circular
1237references. It is exposed to the user via the C<Seen()> call both
1238for writing and reading.
1239
1240If you, as a user, do not need explicit access to the "seen" hash,
1241then you can set the C<Sparseseen> option to allow Data::Dumper
1242to eschew building the "seen" hash for scalars that are known not
1243to possess more than one reference. This speeds up serialization
1244considerably if you use the XS implementation.
1245
1246Note: If you turn on C<Sparseseen>, then you must not rely on the
1247content of the seen hash since its contents will be an
1248implementation detail!
1249
823edd99
GS
1250=back
1251
1252=head2 Exports
1253
1254=over 4
1255
1256=item Dumper
1257
1258=back
1259
1260=head1 EXAMPLES
1261
1262Run these code snippets to get a quick feel for the behavior of this
1263module. When you are through with these examples, you may want to
1264add or change the various configuration variables described above,
1265to see their behavior. (See the testsuite in the Data::Dumper
1266distribution for more examples.)
1267
1268
1269 use Data::Dumper;
1270
1271 package Foo;
1272 sub new {bless {'a' => 1, 'b' => sub { return "foo" }}, $_[0]};
1273
1274 package Fuz; # a weird REF-REF-SCALAR object
1275 sub new {bless \($_ = \ 'fu\'z'), $_[0]};
1276
1277 package main;
1278 $foo = Foo->new;
1279 $fuz = Fuz->new;
1280 $boo = [ 1, [], "abcd", \*foo,
3bd791fa 1281 {1 => 'a', 023 => 'b', 0x45 => 'c'},
823edd99 1282 \\"p\q\'r", $foo, $fuz];
3cb6de81 1283
823edd99
GS
1284 ########
1285 # simple usage
1286 ########
1287
1288 $bar = eval(Dumper($boo));
1289 print($@) if $@;
1290 print Dumper($boo), Dumper($bar); # pretty print (no array indices)
1291
b877fea2
FC
1292 $Data::Dumper::Terse = 1; # don't output names where feasible
1293 $Data::Dumper::Indent = 0; # turn off all pretty print
823edd99
GS
1294 print Dumper($boo), "\n";
1295
b877fea2 1296 $Data::Dumper::Indent = 1; # mild pretty print
823edd99
GS
1297 print Dumper($boo);
1298
b877fea2 1299 $Data::Dumper::Indent = 3; # pretty print with array indices
823edd99
GS
1300 print Dumper($boo);
1301
b877fea2 1302 $Data::Dumper::Useqq = 1; # print strings in double quotes
823edd99 1303 print Dumper($boo);
3cb6de81 1304
b877fea2 1305 $Data::Dumper::Pair = " : "; # specify hash key/value separator
30b4f386 1306 print Dumper($boo);
1307
3cb6de81 1308
823edd99
GS
1309 ########
1310 # recursive structures
1311 ########
3cb6de81 1312
823edd99
GS
1313 @c = ('c');
1314 $c = \@c;
1315 $b = {};
1316 $a = [1, $b, $c];
1317 $b->{a} = $a;
1318 $b->{b} = $a->[1];
1319 $b->{c} = $a->[2];
1320 print Data::Dumper->Dump([$a,$b,$c], [qw(a b c)]);
3cb6de81
GS
1321
1322
823edd99
GS
1323 $Data::Dumper::Purity = 1; # fill in the holes for eval
1324 print Data::Dumper->Dump([$a, $b], [qw(*a b)]); # print as @a
1325 print Data::Dumper->Dump([$b, $a], [qw(*b a)]); # print as %b
3cb6de81
GS
1326
1327
823edd99
GS
1328 $Data::Dumper::Deepcopy = 1; # avoid cross-refs
1329 print Data::Dumper->Dump([$b, $a], [qw(*b a)]);
3cb6de81
GS
1330
1331
823edd99
GS
1332 $Data::Dumper::Purity = 0; # avoid cross-refs
1333 print Data::Dumper->Dump([$b, $a], [qw(*b a)]);
3cb6de81 1334
a2126434
JN
1335 ########
1336 # deep structures
1337 ########
3cb6de81 1338
a2126434
JN
1339 $a = "pearl";
1340 $b = [ $a ];
1341 $c = { 'b' => $b };
1342 $d = [ $c ];
1343 $e = { 'd' => $d };
1344 $f = { 'e' => $e };
1345 print Data::Dumper->Dump([$f], [qw(f)]);
1346
1347 $Data::Dumper::Maxdepth = 3; # no deeper than 3 refs down
1348 print Data::Dumper->Dump([$f], [qw(f)]);
1349
3cb6de81 1350
823edd99
GS
1351 ########
1352 # object-oriented usage
1353 ########
3cb6de81 1354
823edd99
GS
1355 $d = Data::Dumper->new([$a,$b], [qw(a b)]);
1356 $d->Seen({'*c' => $c}); # stash a ref without printing it
1357 $d->Indent(3);
1358 print $d->Dump;
1359 $d->Reset->Purity(0); # empty the seen cache
1360 print join "----\n", $d->Dump;
3cb6de81
GS
1361
1362
823edd99
GS
1363 ########
1364 # persistence
1365 ########
3cb6de81 1366
823edd99
GS
1367 package Foo;
1368 sub new { bless { state => 'awake' }, shift }
1369 sub Freeze {
1370 my $s = shift;
3bd791fa
JK
1371 print STDERR "preparing to sleep\n";
1372 $s->{state} = 'asleep';
1373 return bless $s, 'Foo::ZZZ';
823edd99 1374 }
3cb6de81 1375
823edd99
GS
1376 package Foo::ZZZ;
1377 sub Thaw {
1378 my $s = shift;
3bd791fa
JK
1379 print STDERR "waking up\n";
1380 $s->{state} = 'awake';
1381 return bless $s, 'Foo';
823edd99 1382 }
3cb6de81 1383
3bd791fa 1384 package main;
823edd99
GS
1385 use Data::Dumper;
1386 $a = Foo->new;
1387 $b = Data::Dumper->new([$a], ['c']);
1388 $b->Freezer('Freeze');
1389 $b->Toaster('Thaw');
1390 $c = $b->Dump;
1391 print $c;
1392 $d = eval $c;
1393 print Data::Dumper->Dump([$d], ['d']);
3cb6de81
GS
1394
1395
823edd99
GS
1396 ########
1397 # symbol substitution (useful for recreating CODE refs)
1398 ########
3cb6de81 1399
823edd99
GS
1400 sub foo { print "foo speaking\n" }
1401 *other = \&foo;
1402 $bar = [ \&other ];
1403 $d = Data::Dumper->new([\&other,$bar],['*other','bar']);
1404 $d->Seen({ '*foo' => \&foo });
1405 print $d->Dump;
1406
1407
31a725b3
JH
1408 ########
1409 # sorting and filtering hash keys
1410 ########
1411
1412 $Data::Dumper::Sortkeys = \&my_filter;
1413 my $foo = { map { (ord, "$_$_$_") } 'I'..'Q' };
1414 my $bar = { %$foo };
1415 my $baz = { reverse %$foo };
1416 print Dumper [ $foo, $bar, $baz ];
1417
1418 sub my_filter {
1419 my ($hash) = @_;
1420 # return an array ref containing the hash keys to dump
1421 # in the order that you want them to be dumped
1422 return [
1423 # Sort the keys of %$foo in reverse numeric order
1424 $hash eq $foo ? (sort {$b <=> $a} keys %$hash) :
1425 # Only dump the odd number keys of %$bar
1426 $hash eq $bar ? (grep {$_ % 2} keys %$hash) :
1427 # Sort keys in default order for all other hashes
1428 (sort keys %$hash)
1429 ];
1430 }
1431
823edd99
GS
1432=head1 BUGS
1433
1434Due to limitations of Perl subroutine call semantics, you cannot pass an
1435array or hash. Prepend it with a C<\> to pass its reference instead. This
8e5f9a6e
RGS
1436will be remedied in time, now that Perl has subroutine prototypes.
1437For now, you need to use the extended usage form, and prepend the
823edd99
GS
1438name with a C<*> to output it as a hash or array.
1439
1440C<Data::Dumper> cheats with CODE references. If a code reference is
8e5f9a6e
RGS
1441encountered in the structure being processed (and if you haven't set
1442the C<Deparse> flag), an anonymous subroutine that
823edd99
GS
1443contains the string '"DUMMY"' will be inserted in its place, and a warning
1444will be printed if C<Purity> is set. You can C<eval> the result, but bear
1445in mind that the anonymous sub that gets created is just a placeholder.
b5048e7b
AC
1446Even using the C<Deparse> flag will in some cases produce results that
1447behave differently after being passed to C<eval>; see the documentation
1448for L<B::Deparse>.
823edd99
GS
1449
1450SCALAR objects have the weirdest looking C<bless> workaround.
1451
fec5e1eb
IM
1452Pure Perl version of C<Data::Dumper> escapes UTF-8 strings correctly
1453only in Perl 5.8.0 and later.
1454
504f80c1
JH
1455=head2 NOTE
1456
1457Starting from Perl 5.8.1 different runs of Perl will have different
1458ordering of hash keys. The change was done for greater security,
1459see L<perlsec/"Algorithmic Complexity Attacks">. This means that
1460different runs of Perl will have different Data::Dumper outputs if
1461the data contains hashes. If you need to have identical Data::Dumper
1462outputs from different runs of Perl, use the environment variable
1463PERL_HASH_SEED, see L<perlrun/PERL_HASH_SEED>. Using this restores
1464the old (platform-specific) ordering: an even prettier solution might
1465be to use the C<Sortkeys> filter of Data::Dumper.
823edd99
GS
1466
1467=head1 AUTHOR
1468
6e238990 1469Gurusamy Sarathy gsar@activestate.com
823edd99 1470
8235b1c2 1471Copyright (c) 1996-2017 Gurusamy Sarathy. All rights reserved.
823edd99
GS
1472This program is free software; you can redistribute it and/or
1473modify it under the same terms as Perl itself.
1474
823edd99
GS
1475=head1 VERSION
1476
fb504317 1477Version 2.170
823edd99
GS
1478
1479=head1 SEE ALSO
1480
1481perl(1)
1482
1483=cut