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