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