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