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