4 # convert perl data structures into perl syntax suitable for both printing
7 # Documentation at the __END__
25 @EXPORT_OK = qw(DumperX);
27 XSLoader::load 'Data::Dumper';
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;
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.
55 croak "Usage: PACKAGE->new(ARRAYREF, [ARRAYREF])"
56 unless (defined($v) && (ref($v) eq 'ARRAY'));
57 $n = [] unless (defined($n) && (ref($v) eq 'ARRAY'));
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
92 # add-to or query the table of already seen references
96 if (defined($g) && (ref($g) eq 'HASH')) {
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 ) :
107 elsif ($k !~ /^\$/) {
110 $s->{seen}{$id} = [$k, $v];
113 carp "Only refs supported, ignoring non-ref item \$$k";
119 return map { @$_ } values %{$s->{seen}};
124 # set or query the values to be dumped
128 if (defined($v) && (ref($v) eq 'ARRAY')) {
129 $s->{todump} = [@$v]; # make a copy
133 return @{$s->{todump}};
138 # set or query the names of the values to be dumped
142 if (defined($n) && (ref($n) eq 'ARRAY')) {
143 $s->{names} = [@$n]; # make a copy
147 return @{$s->{names}};
155 unless $Data::Dumper::Useperl || (ref($_[0]) && $_[0]->{useperl}) ||
156 $Data::Dumper::Useqq || (ref($_[0]) && $_[0]->{useqq});
161 # dump the refs in the current dumper object.
162 # expects same args as new() if called via package name.
166 my(@out, $val, $name);
170 $s = $s->new(@_) unless ref $s;
172 for $val (@{$s->{todump}}) {
175 $name = $s->{names}[$i++];
177 if ($name =~ /^[*](.*)$/) {
179 $name = (ref $val eq 'ARRAY') ? ( "\@" . $1 ) :
180 (ref $val eq 'HASH') ? ( "\%" . $1 ) :
181 (ref $val eq 'CODE') ? ( "\*" . $1 ) :
188 elsif ($name !~ /^\$/) {
189 $name = "\$" . $name;
193 $name = "\$" . $s->{varname} . $i;
198 local($s->{apad}) = $s->{apad};
199 $s->{apad} .= ' ' x (length($name) + 3) if $s->{indent} >= 2;
200 $valstr = $s->_dump($val, $name);
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;
210 return wantarray ? @out : join('', @out);
214 # twist, toil and turn;
215 # and recurse, of course.
216 # sometimes sordidly;
217 # and curse if no recourse.
220 my($s, $val, $name) = @_;
222 my($out, $realpack, $realtype, $type, $ipad, $id, $blesspad);
229 # prep it, if it looks like an object
230 if (my $freezer = $s->{freezer}) {
231 $val->$freezer() if UNIVERSAL::can($val, $freezer);
234 ($realpack, $realtype, $id) =
235 (overload::StrVal($val) =~ /^(?:(.*)\=)?([^=]*)\(([^\(]*)\)$/);
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') ? '[]' :
247 push @post, $name . " = " . $s->{seen}{$id}[0];
250 $out = $s->{seen}{$id}[0];
251 if ($name =~ /^([\@\%])/) {
253 if ($out =~ /^\\$start/) {
254 $out = substr($out, 1);
257 $out = $start . '{' . $out . '}';
266 $s->{seen}{$id} = [ (($name =~ /^[@%]/) ? ('\\' . $name ) :
267 ($realtype eq 'CODE' and
268 $name =~ /^[*](.*)$/) ? ('\\&' . $1 ) :
274 if ($realpack and $realpack eq 'Regexp') {
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)').
285 and $s->{maxdepth} > 0
286 and $s->{level} >= $s->{maxdepth})
291 # we have a blessed ref
293 $out = $s->{'bless'} . '( ';
294 $blesspad = $s->{apad};
295 $s->{apad} .= ' ' if ($s->{indent} >= 2);
299 $ipad = $s->{xpad} x $s->{level};
301 if ($realtype eq 'SCALAR' || $realtype eq 'REF') {
303 $out .= 'do{\\(my $o = ' . $s->_dump($$val, "\${$name}") . ')}';
306 $out .= '\\' . $s->_dump($$val, "\${$name}");
309 elsif ($realtype eq 'GLOB') {
310 $out .= '\\' . $s->_dump($$val, "*{$name}");
312 elsif ($realtype eq 'ARRAY') {
313 my($v, $pad, $mname);
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]+\}$/;
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;
328 $out .= $pad . ($s->{xpad} x ($s->{level} - 1)) if $i;
329 $out .= ($name =~ /^\@/) ? ')' : ']';
331 elsif ($realtype eq 'HASH') {
332 my($k, $v, $pad, $lpad, $mname);
333 $out .= ($name =~ /^\%/) ? '(' : '{';
334 $pad = $s->{sep} . $s->{pad} . $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}");
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";
351 $keys = [ sort keys %$val ];
354 while (($k, $v) = ! $sortkeys ? (each %$val) :
355 @$keys ? ($key = shift(@$keys), $val->{$key}) :
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 . " => ";
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;
368 if (substr($out, -1) eq ',') {
370 $out .= $pad . ($s->{xpad} x ($s->{level} - 1));
372 $out .= ($name =~ /^\%/) ? ')' : '}';
374 elsif ($realtype eq 'CODE') {
375 $out .= 'sub { "DUMMY" }';
376 carp "Encountered CODE ref, using dummy placeholder" if $s->{purity};
379 croak "Can\'t handle $realtype type.";
382 if ($realpack) { # we have a blessed ref
383 $out .= ', \'' . $realpack . '\'' . ' )';
384 $out .= '->' . $s->{toaster} . '()' if $s->{toaster} ne '';
385 $s->{apad} = $blesspad;
390 else { # simple scalar
393 # first, catalog the scalar
395 ($id) = ("$ref" =~ /\(([^\(]*)\)$/);
396 if (exists $s->{seen}{$id}) {
397 if ($s->{seen}{$id}[2]) {
398 $out = $s->{seen}{$id}[0];
404 #warn "[>\\$name]\n";
405 $s->{seen}{$id} = ["\\$name", $ref];
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::/::/;
415 $sname = $s->_dump($name, "");
416 $sname = '{' . $sname . '}';
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
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\}");
433 $out .= '*' . $sname;
435 elsif (!defined($val)) {
438 elsif ($val =~ /^(?:0|-?[1-9]\d{0,8})$/) { # safe decimal number
443 $out .= qquote($val, $s->{useqq});
446 $val =~ s/([\\\'])/\\$1/g;
447 $out .= '\'' . $val . '\'';
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});
458 $s->{seen}{$id}[2] = 1;
465 # non-OO style of earlier version
468 return Data::Dumper->Dump([@_]);
473 return Data::Dumper->Dumpxs([@_], []);
476 sub Dumpf { return Data::Dumper->Dump(@_) }
478 sub Dumpp { print Data::Dumper->Dump(@_) }
481 # reset the "seen" cache
510 defined($v) ? (($s->{pad} = $v), return $s) : $s->{pad};
515 defined($v) ? (($s->{varname} = $v), return $s) : $s->{varname};
520 defined($v) ? (($s->{purity} = $v), return $s) : $s->{purity};
525 defined($v) ? (($s->{useqq} = $v), return $s) : $s->{useqq};
530 defined($v) ? (($s->{terse} = $v), return $s) : $s->{terse};
535 defined($v) ? (($s->{freezer} = $v), return $s) : $s->{freezer};
540 defined($v) ? (($s->{toaster} = $v), return $s) : $s->{toaster};
545 defined($v) ? (($s->{deepcopy} = $v), return $s) : $s->{deepcopy};
550 defined($v) ? (($s->{quotekeys} = $v), return $s) : $s->{quotekeys};
555 defined($v) ? (($s->{'bless'} = $v), return $s) : $s->{'bless'};
560 defined($v) ? (($s->{'maxdepth'} = $v), return $s) : $s->{'maxdepth'};
565 defined($v) ? (($s->{'useperl'} = $v), return $s) : $s->{'useperl'};
570 defined($v) ? (($s->{'sortkeys'} = $v), return $s) : $s->{'sortkeys'};
574 # used by qquote below
585 # put a string value in double quotes
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
594 my $high = shift || "";
595 s/([\a\b\t\n\f\r\e])/$esc{$1}/g;
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") {
606 # $str =~ s/([^\040-\176])/sprintf "\\x{%04x}", ord($1)/ge;
607 } elsif ($high eq "8bit") {
610 s/([\200-\377])/'\\'.sprintf('%03o',ord($1))/eg;
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;
628 Data::Dumper - stringified perl data structures, suitable for both printing and C<eval>
634 # simple procedural interface
635 print Dumper($foo, $bar);
637 # extended usage with names
638 print Data::Dumper->Dump([$foo, $bar], [qw(foo *ary)]);
640 # configuration variables
642 local $Data::Dump::Purity = 1;
643 eval Data::Dumper->Dump([$foo, $bar], [qw(foo *ary)]);
647 $d = Data::Dumper->new([$foo, $bar], [qw(foo *ary)]);
651 $d->Purity(1)->Terse(1)->Deepcopy(1);
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.
662 The return value can be C<eval>ed to get back an identical copy of the
663 original reference structure.
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>
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
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.
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
689 Several styles of output are possible, all controlled by setting
690 the C<Indent> flag. See L<Configuration Variables or Methods> below
698 =item I<PACKAGE>->new(I<ARRAYREF [>, I<ARRAYREF]>)
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.
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.
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
717 =item I<$OBJ>->Dump I<or> I<PACKAGE>->Dump(I<ARRAYREF [>, I<ARRAYREF]>)
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.
724 The second form, for convenience, simply calls the C<new> method on its
725 arguments before dumping the object immediately.
727 =item I<$OBJ>->Seen(I<[HASHREF]>)
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.
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
740 =item I<$OBJ>->Values(I<[ARRAYREF]>)
742 Queries or replaces the internal array of values that will be dumped.
743 When called without arguments, returns the values. Otherwise, returns the
746 =item I<$OBJ>->Names(I<[ARRAYREF]>)
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.
754 Clears the internal table of "seen" references and returns the object
763 =item Dumper(I<LIST>)
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
772 =head2 Configuration Variables or Methods
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
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.
784 The method forms return the object itself when called with arguments,
785 so that they can be chained together nicely.
789 =item $Data::Dumper::Indent I<or> I<$OBJ>->Indent(I<[NEWVAL]>)
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.
802 =item $Data::Dumper::Purity I<or> I<$OBJ>->Purity(I<[NEWVAL]>)
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
809 =item $Data::Dumper::Pad I<or> I<$OBJ>->Pad(I<[NEWVAL]>)
811 Specifies the string that will be prefixed to every line of the output.
812 Empty string by default.
814 =item $Data::Dumper::Varname I<or> I<$OBJ>->Varname(I<[NEWVAL]>)
816 Contains the prefix to use for tagging variable names in the output. The
819 =item $Data::Dumper::Useqq I<or> I<$OBJ>->Useqq(I<[NEWVAL]>)
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.
828 =item $Data::Dumper::Terse I<or> I<$OBJ>->Terse(I<[NEWVAL]>)
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>.
835 =item $Data::Dumper::Freezer I<or> $I<OBJ>->Freezer(I<[NEWVAL]>)
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
846 =item $Data::Dumper::Toaster I<or> $I<OBJ>->Toaster(I<[NEWVAL]>)
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.
857 =item $Data::Dumper::Deepcopy I<or> $I<OBJ>->Deepcopy(I<[NEWVAL]>)
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.
863 =item $Data::Dumper::Quotekeys I<or> $I<OBJ>->Quotekeys(I<[NEWVAL]>)
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.
869 =item $Data::Dumper::Bless I<or> $I<OBJ>->Bless(I<[NEWVAL]>)
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.
876 =item $Data::Dumper::Maxdepth I<or> $I<OBJ>->Maxdepth(I<[NEWVAL]>)
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
884 =item $Data::Dumper::Useperl I<or> $I<OBJ>->Useperl(I<[NEWVAL]>)
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.
894 =item $Data::Dumper::Sortkeys I<or> $I<OBJ>->Sortkeys(I<[NEWVAL]>)
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
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.)
931 sub new {bless {'a' => 1, 'b' => sub { return "foo" }}, $_[0]};
933 package Fuz; # a weird REF-REF-SCALAR object
934 sub new {bless \($_ = \ 'fu\'z'), $_[0]};
939 $boo = [ 1, [], "abcd", \*foo,
940 {1 => 'a', 023 => 'b', 0x45 => 'c'},
941 \\"p\q\'r", $foo, $fuz];
947 $bar = eval(Dumper($boo));
949 print Dumper($boo), Dumper($bar); # pretty print (no array indices)
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";
955 $Data::Dumper::Indent = 1; # mild pretty print
958 $Data::Dumper::Indent = 3; # pretty print with array indices
961 $Data::Dumper::Useqq = 1; # print strings in double quotes
966 # recursive structures
976 print Data::Dumper->Dump([$a,$b,$c], [qw(a b c)]);
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
984 $Data::Dumper::Deepcopy = 1; # avoid cross-refs
985 print Data::Dumper->Dump([$b, $a], [qw(*b a)]);
988 $Data::Dumper::Purity = 0; # avoid cross-refs
989 print Data::Dumper->Dump([$b, $a], [qw(*b a)]);
1001 print Data::Dumper->Dump([$f], [qw(f)]);
1003 $Data::Dumper::Maxdepth = 3; # no deeper than 3 refs down
1004 print Data::Dumper->Dump([$f], [qw(f)]);
1008 # object-oriented usage
1011 $d = Data::Dumper->new([$a,$b], [qw(a b)]);
1012 $d->Seen({'*c' => $c}); # stash a ref without printing it
1015 $d->Reset->Purity(0); # empty the seen cache
1016 print join "----\n", $d->Dump;
1024 sub new { bless { state => 'awake' }, shift }
1027 print STDERR "preparing to sleep\n";
1028 $s->{state} = 'asleep';
1029 return bless $s, 'Foo::ZZZ';
1035 print STDERR "waking up\n";
1036 $s->{state} = 'awake';
1037 return bless $s, 'Foo';
1043 $b = Data::Dumper->new([$a], ['c']);
1044 $b->Freezer('Freeze');
1045 $b->Toaster('Thaw');
1049 print Data::Dumper->Dump([$d], ['d']);
1053 # symbol substitution (useful for recreating CODE refs)
1056 sub foo { print "foo speaking\n" }
1059 $d = Data::Dumper->new([\&other,$bar],['*other','bar']);
1060 $d->Seen({ '*foo' => \&foo });
1065 # sorting and filtering hash keys
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 ];
1076 # return an array ref containing the hash keys to dump
1077 # in the order that you want them to be dumped
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
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.
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>
1108 The C<Useqq> flag makes Dump() run slower, since the XSUB implementation
1109 does not support it.
1111 SCALAR objects have the weirdest looking C<bless> workaround.
1116 Gurusamy Sarathy gsar@activestate.com
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.
1125 Version 2.11 (unreleased)