1Data::Dumper(3pm)      Perl Programmers Reference Guide      Data::Dumper(3pm)
2
3
4

NAME

6       Data::Dumper - stringified perl data structures, suitable for both
7       printing and "eval"
8

SYNOPSIS

10           use Data::Dumper;
11
12           # simple procedural interface
13           print Dumper($foo, $bar);
14
15           # extended usage with names
16           print Data::Dumper->Dump([$foo, $bar], [qw(foo *ary)]);
17
18           # configuration variables
19           {
20             local $Data::Dumper::Purity = 1;
21             eval Data::Dumper->Dump([$foo, $bar], [qw(foo *ary)]);
22           }
23
24           # OO usage
25           $d = Data::Dumper->new([$foo, $bar], [qw(foo *ary)]);
26              ...
27           print $d->Dump;
28              ...
29           $d->Purity(1)->Terse(1)->Deepcopy(1);
30           eval $d->Dump;
31

DESCRIPTION

33       Given a list of scalars or reference variables, writes out their con‐
34       tents in perl syntax. The references can also be objects.  The contents
35       of each variable is output in a single Perl statement.  Handles self-
36       referential structures correctly.
37
38       The return value can be "eval"ed to get back an identical copy of the
39       original reference structure.
40
41       Any references that are the same as one of those passed in will be
42       named $VARn (where n is a numeric suffix), and other duplicate refer‐
43       ences to substructures within $VARn will be appropriately labeled using
44       arrow notation.  You can specify names for individual values to be
45       dumped if you use the "Dump()" method, or you can change the default
46       $VAR prefix to something else.  See $Data::Dumper::Varname and
47       $Data::Dumper::Terse below.
48
49       The default output of self-referential structures can be "eval"ed, but
50       the nested references to $VARn will be undefined, since a recursive
51       structure cannot be constructed using one Perl statement.  You should
52       set the "Purity" flag to 1 to get additional statements that will cor‐
53       rectly fill in these references.  Moreover, if "eval"ed when strictures
54       are in effect, you need to ensure that any variables it accesses are
55       previously declared.
56
57       In the extended usage form, the references to be dumped can be given
58       user-specified names.  If a name begins with a "*", the output will
59       describe the dereferenced type of the supplied reference for hashes and
60       arrays, and coderefs.  Output of names will be avoided where possible
61       if the "Terse" flag is set.
62
63       In many cases, methods that are used to set the internal state of the
64       object will return the object itself, so method calls can be conve‐
65       niently chained together.
66
67       Several styles of output are possible, all controlled by setting the
68       "Indent" flag.  See "Configuration Variables or Methods" below for
69       details.
70
71       Methods
72
73       PACKAGE->new(ARRAYREF [, ARRAYREF])
74           Returns a newly created "Data::Dumper" object.  The first argument
75           is an anonymous array of values to be dumped.  The optional second
76           argument is an anonymous array of names for the values.  The names
77           need not have a leading "$" sign, and must be comprised of alphanu‐
78           meric characters.  You can begin a name with a "*" to specify that
79           the dereferenced type must be dumped instead of the reference
80           itself, for ARRAY and HASH references.
81
82           The prefix specified by $Data::Dumper::Varname will be used with a
83           numeric suffix if the name for a value is undefined.
84
85           Data::Dumper will catalog all references encountered while dumping
86           the values. Cross-references (in the form of names of substructures
87           in perl syntax) will be inserted at all possible points, preserving
88           any structural interdependencies in the original set of values.
89           Structure traversal is depth-first,  and proceeds in order from the
90           first supplied value to the last.
91
92       $OBJ->Dump  or  PACKAGE->Dump(ARRAYREF [, ARRAYREF])
93           Returns the stringified form of the values stored in the object
94           (preserving the order in which they were supplied to "new"), sub‐
95           ject to the configuration options below.  In a list context, it
96           returns a list of strings corresponding to the supplied values.
97
98           The second form, for convenience, simply calls the "new" method on
99           its arguments before dumping the object immediately.
100
101       $OBJ->Seen([HASHREF])
102           Queries or adds to the internal table of already encountered refer‐
103           ences.  You must use "Reset" to explicitly clear the table if
104           needed.  Such references are not dumped; instead, their names are
105           inserted wherever they are encountered subsequently.  This is use‐
106           ful especially for properly dumping subroutine references.
107
108           Expects an anonymous hash of name => value pairs.  Same rules apply
109           for names as in "new".  If no argument is supplied, will return the
110           "seen" list of name => value pairs, in a list context.  Otherwise,
111           returns the object itself.
112
113       $OBJ->Values([ARRAYREF])
114           Queries or replaces the internal array of values that will be
115           dumped.  When called without arguments, returns the values.  Other‐
116           wise, returns the object itself.
117
118       $OBJ->Names([ARRAYREF])
119           Queries or replaces the internal array of user supplied names for
120           the values that will be dumped.  When called without arguments,
121           returns the names.  Otherwise, returns the object itself.
122
123       $OBJ->Reset
124           Clears the internal table of "seen" references and returns the
125           object itself.
126
127       Functions
128
129       Dumper(LIST)
130           Returns the stringified form of the values in the list, subject to
131           the configuration options below.  The values will be named $VARn in
132           the output, where n is a numeric suffix.  Will return a list of
133           strings in a list context.
134
135       Configuration Variables or Methods
136
137       Several configuration variables can be used to control the kind of out‐
138       put generated when using the procedural interface.  These variables are
139       usually "local"ized in a block so that other parts of the code are not
140       affected by the change.
141
142       These variables determine the default state of the object created by
143       calling the "new" method, but cannot be used to alter the state of the
144       object thereafter.  The equivalent method names should be used instead
145       to query or set the internal state of the object.
146
147       The method forms return the object itself when called with arguments,
148       so that they can be chained together nicely.
149
150       ·   $Data::Dumper::Indent  or  $OBJ->Indent([NEWVAL])
151
152           Controls the style of indentation.  It can be set to 0, 1, 2 or 3.
153           Style 0 spews output without any newlines, indentation, or spaces
154           between list items.  It is the most compact format possible that
155           can still be called valid perl.  Style 1 outputs a readable form
156           with newlines but no fancy indentation (each level in the structure
157           is simply indented by a fixed amount of whitespace).  Style 2 (the
158           default) outputs a very readable form which takes into account the
159           length of hash keys (so the hash value lines up).  Style 3 is like
160           style 2, but also annotates the elements of arrays with their index
161           (but the comment is on its own line, so array output consumes twice
162           the number of lines).  Style 2 is the default.
163
164       ·   $Data::Dumper::Purity  or  $OBJ->Purity([NEWVAL])
165
166           Controls the degree to which the output can be "eval"ed to recreate
167           the supplied reference structures.  Setting it to 1 will output
168           additional perl statements that will correctly recreate nested ref‐
169           erences.  The default is 0.
170
171       ·   $Data::Dumper::Pad  or  $OBJ->Pad([NEWVAL])
172
173           Specifies the string that will be prefixed to every line of the
174           output.  Empty string by default.
175
176       ·   $Data::Dumper::Varname  or  $OBJ->Varname([NEWVAL])
177
178           Contains the prefix to use for tagging variable names in the out‐
179           put. The default is "VAR".
180
181       ·   $Data::Dumper::Useqq  or  $OBJ->Useqq([NEWVAL])
182
183           When set, enables the use of double quotes for representing string
184           values.  Whitespace other than space will be represented as
185           "[\n\t\r]", "unsafe" characters will be backslashed, and unprint‐
186           able characters will be output as quoted octal integers.  Since
187           setting this variable imposes a performance penalty, the default is
188           0.  "Dump()" will run slower if this flag is set, since the fast
189           XSUB implementation doesn't support it yet.
190
191       ·   $Data::Dumper::Terse  or  $OBJ->Terse([NEWVAL])
192
193           When set, Data::Dumper will emit single, non-self-referential val‐
194           ues as atoms/terms rather than statements.  This means that the
195           $VARn names will be avoided where possible, but be advised that
196           such output may not always be parseable by "eval".
197
198       ·   $Data::Dumper::Freezer  or  $OBJ->Freezer([NEWVAL])
199
200           Can be set to a method name, or to an empty string to disable the
201           feature.  Data::Dumper will invoke that method via the object
202           before attempting to stringify it.  This method can alter the con‐
203           tents of the object (if, for instance, it contains data allocated
204           from C), and even rebless it in a different package.  The client is
205           responsible for making sure the specified method can be called via
206           the object, and that the object ends up containing only perl data
207           types after the method has been called.  Defaults to an empty
208           string.
209
210           If an object does not support the method specified (determined
211           using UNIVERSAL::can()) then the call will be skipped.  If the
212           method dies a warning will be generated.
213
214       ·   $Data::Dumper::Toaster  or  $OBJ->Toaster([NEWVAL])
215
216           Can be set to a method name, or to an empty string to disable the
217           feature.  Data::Dumper will emit a method call for any objects that
218           are to be dumped using the syntax "bless(DATA, CLASS)->METHOD()".
219           Note that this means that the method specified will have to perform
220           any modifications required on the object (like creating new state
221           within it, and/or reblessing it in a different package) and then
222           return it.  The client is responsible for making sure the method
223           can be called via the object, and that it returns a valid object.
224           Defaults to an empty string.
225
226       ·   $Data::Dumper::Deepcopy  or  $OBJ->Deepcopy([NEWVAL])
227
228           Can be set to a boolean value to enable deep copies of structures.
229           Cross-referencing will then only be done when absolutely essential
230           (i.e., to break reference cycles).  Default is 0.
231
232       ·   $Data::Dumper::Quotekeys  or  $OBJ->Quotekeys([NEWVAL])
233
234           Can be set to a boolean value to control whether hash keys are
235           quoted.  A false value will avoid quoting hash keys when it looks
236           like a simple string.  Default is 1, which will always enclose hash
237           keys in quotes.
238
239       ·   $Data::Dumper::Bless  or  $OBJ->Bless([NEWVAL])
240
241           Can be set to a string that specifies an alternative to the "bless"
242           builtin operator used to create objects.  A function with the spec‐
243           ified name should exist, and should accept the same arguments as
244           the builtin.  Default is "bless".
245
246       ·   $Data::Dumper::Pair  or  $OBJ->Pair([NEWVAL])
247
248           Can be set to a string that specifies the separator between hash
249           keys and values. To dump nested hash, array and scalar values to
250           JavaScript, use: "$Data::Dumper::Pair = ' : ';". Implementing
251           "bless" in JavaScript is left as an exercise for the reader.  A
252           function with the specified name exists, and accepts the same argu‐
253           ments as the builtin.
254
255           Default is: " => ".
256
257       ·   $Data::Dumper::Maxdepth  or  $OBJ->Maxdepth([NEWVAL])
258
259           Can be set to a positive integer that specifies the depth beyond
260           which which we don't venture into a structure.  Has no effect when
261           "Data::Dumper::Purity" is set.  (Useful in debugger when we often
262           don't want to see more than enough).  Default is 0, which means
263           there is no maximum depth.
264
265       ·   $Data::Dumper::Useperl  or  $OBJ->Useperl([NEWVAL])
266
267           Can be set to a boolean value which controls whether the pure Perl
268           implementation of "Data::Dumper" is used. The "Data::Dumper" module
269           is a dual implementation, with almost all functionality written in
270           both pure Perl and also in XS ('C'). Since the XS version is much
271           faster, it will always be used if possible. This option lets you
272           override the default behavior, usually for testing purposes only.
273           Default is 0, which means the XS implementation will be used if
274           possible.
275
276       ·   $Data::Dumper::Sortkeys  or  $OBJ->Sortkeys([NEWVAL])
277
278           Can be set to a boolean value to control whether hash keys are
279           dumped in sorted order. A true value will cause the keys of all
280           hashes to be dumped in Perl's default sort order. Can also be set
281           to a subroutine reference which will be called for each hash that
282           is dumped. In this case "Data::Dumper" will call the subroutine
283           once for each hash, passing it the reference of the hash. The pur‐
284           pose of the subroutine is to return a reference to an array of the
285           keys that will be dumped, in the order that they should be dumped.
286           Using this feature, you can control both the order of the keys, and
287           which keys are actually used. In other words, this subroutine acts
288           as a filter by which you can exclude certain keys from being
289           dumped. Default is 0, which means that hash keys are not sorted.
290
291       ·   $Data::Dumper::Deparse  or  $OBJ->Deparse([NEWVAL])
292
293           Can be set to a boolean value to control whether code references
294           are turned into perl source code. If set to a true value,
295           "B::Deparse" will be used to get the source of the code reference.
296           Using this option will force using the Perl implementation of the
297           dumper, since the fast XSUB implementation doesn't support it.
298
299           Caution : use this option only if you know that your coderefs will
300           be properly reconstructed by "B::Deparse".
301
302       Exports
303
304       Dumper
305

EXAMPLES

307       Run these code snippets to get a quick feel for the behavior of this
308       module.  When you are through with these examples, you may want to add
309       or change the various configuration variables described above, to see
310       their behavior.  (See the testsuite in the Data::Dumper distribution
311       for more examples.)
312
313           use Data::Dumper;
314
315           package Foo;
316           sub new {bless {'a' => 1, 'b' => sub { return "foo" }}, $_[0]};
317
318           package Fuz;                       # a weird REF-REF-SCALAR object
319           sub new {bless \($_ = \ 'fu\'z'), $_[0]};
320
321           package main;
322           $foo = Foo->new;
323           $fuz = Fuz->new;
324           $boo = [ 1, [], "abcd", \*foo,
325                    {1 => 'a', 023 => 'b', 0x45 => 'c'},
326                    \\"p\q\'r", $foo, $fuz];
327
328           ########
329           # simple usage
330           ########
331
332           $bar = eval(Dumper($boo));
333           print($@) if $@;
334           print Dumper($boo), Dumper($bar);  # pretty print (no array indices)
335
336           $Data::Dumper::Terse = 1;          # don't output names where feasible
337           $Data::Dumper::Indent = 0;         # turn off all pretty print
338           print Dumper($boo), "\n";
339
340           $Data::Dumper::Indent = 1;         # mild pretty print
341           print Dumper($boo);
342
343           $Data::Dumper::Indent = 3;         # pretty print with array indices
344           print Dumper($boo);
345
346           $Data::Dumper::Useqq = 1;          # print strings in double quotes
347           print Dumper($boo);
348
349           $Data::Dumper::Pair = " : ";       # specify hash key/value separator
350           print Dumper($boo);
351
352           ########
353           # recursive structures
354           ########
355
356           @c = ('c');
357           $c = \@c;
358           $b = {};
359           $a = [1, $b, $c];
360           $b->{a} = $a;
361           $b->{b} = $a->[1];
362           $b->{c} = $a->[2];
363           print Data::Dumper->Dump([$a,$b,$c], [qw(a b c)]);
364
365           $Data::Dumper::Purity = 1;         # fill in the holes for eval
366           print Data::Dumper->Dump([$a, $b], [qw(*a b)]); # print as @a
367           print Data::Dumper->Dump([$b, $a], [qw(*b a)]); # print as %b
368
369           $Data::Dumper::Deepcopy = 1;       # avoid cross-refs
370           print Data::Dumper->Dump([$b, $a], [qw(*b a)]);
371
372           $Data::Dumper::Purity = 0;         # avoid cross-refs
373           print Data::Dumper->Dump([$b, $a], [qw(*b a)]);
374
375           ########
376           # deep structures
377           ########
378
379           $a = "pearl";
380           $b = [ $a ];
381           $c = { 'b' => $b };
382           $d = [ $c ];
383           $e = { 'd' => $d };
384           $f = { 'e' => $e };
385           print Data::Dumper->Dump([$f], [qw(f)]);
386
387           $Data::Dumper::Maxdepth = 3;       # no deeper than 3 refs down
388           print Data::Dumper->Dump([$f], [qw(f)]);
389
390           ########
391           # object-oriented usage
392           ########
393
394           $d = Data::Dumper->new([$a,$b], [qw(a b)]);
395           $d->Seen({'*c' => $c});            # stash a ref without printing it
396           $d->Indent(3);
397           print $d->Dump;
398           $d->Reset->Purity(0);              # empty the seen cache
399           print join "----\n", $d->Dump;
400
401           ########
402           # persistence
403           ########
404
405           package Foo;
406           sub new { bless { state => 'awake' }, shift }
407           sub Freeze {
408               my $s = shift;
409               print STDERR "preparing to sleep\n";
410               $s->{state} = 'asleep';
411               return bless $s, 'Foo::ZZZ';
412           }
413
414           package Foo::ZZZ;
415           sub Thaw {
416               my $s = shift;
417               print STDERR "waking up\n";
418               $s->{state} = 'awake';
419               return bless $s, 'Foo';
420           }
421
422           package Foo;
423           use Data::Dumper;
424           $a = Foo->new;
425           $b = Data::Dumper->new([$a], ['c']);
426           $b->Freezer('Freeze');
427           $b->Toaster('Thaw');
428           $c = $b->Dump;
429           print $c;
430           $d = eval $c;
431           print Data::Dumper->Dump([$d], ['d']);
432
433           ########
434           # symbol substitution (useful for recreating CODE refs)
435           ########
436
437           sub foo { print "foo speaking\n" }
438           *other = \&foo;
439           $bar = [ \&other ];
440           $d = Data::Dumper->new([\&other,$bar],['*other','bar']);
441           $d->Seen({ '*foo' => \&foo });
442           print $d->Dump;
443
444           ########
445           # sorting and filtering hash keys
446           ########
447
448           $Data::Dumper::Sortkeys = \&my_filter;
449           my $foo = { map { (ord, "$_$_$_") } 'I'..'Q' };
450           my $bar = { %$foo };
451           my $baz = { reverse %$foo };
452           print Dumper [ $foo, $bar, $baz ];
453
454           sub my_filter {
455               my ($hash) = @_;
456               # return an array ref containing the hash keys to dump
457               # in the order that you want them to be dumped
458               return [
459                 # Sort the keys of %$foo in reverse numeric order
460                   $hash eq $foo ? (sort {$b <=> $a} keys %$hash) :
461                 # Only dump the odd number keys of %$bar
462                   $hash eq $bar ? (grep {$_ % 2} keys %$hash) :
463                 # Sort keys in default order for all other hashes
464                   (sort keys %$hash)
465               ];
466           }
467

BUGS

469       Due to limitations of Perl subroutine call semantics, you cannot pass
470       an array or hash.  Prepend it with a "\" to pass its reference instead.
471       This will be remedied in time, now that Perl has subroutine prototypes.
472       For now, you need to use the extended usage form, and prepend the name
473       with a "*" to output it as a hash or array.
474
475       "Data::Dumper" cheats with CODE references.  If a code reference is
476       encountered in the structure being processed (and if you haven't set
477       the "Deparse" flag), an anonymous subroutine that contains the string
478       '"DUMMY"' will be inserted in its place, and a warning will be printed
479       if "Purity" is set.  You can "eval" the result, but bear in mind that
480       the anonymous sub that gets created is just a placeholder.  Someday,
481       perl will have a switch to cache-on-demand the string representation of
482       a compiled piece of code, I hope.  If you have prior knowledge of all
483       the code refs that your data structures are likely to have, you can use
484       the "Seen" method to pre-seed the internal reference table and make the
485       dumped output point to them, instead.  See "EXAMPLES" above.
486
487       The "Useqq" and "Deparse" flags makes Dump() run slower, since the XSUB
488       implementation does not support them.
489
490       SCALAR objects have the weirdest looking "bless" workaround.
491
492       Pure Perl version of "Data::Dumper" escapes UTF-8 strings correctly
493       only in Perl 5.8.0 and later.
494
495       NOTE
496
497       Starting from Perl 5.8.1 different runs of Perl will have different
498       ordering of hash keys.  The change was done for greater security, see
499       "Algorithmic Complexity Attacks" in perlsec.  This means that different
500       runs of Perl will have different Data::Dumper outputs if the data con‐
501       tains hashes.  If you need to have identical Data::Dumper outputs from
502       different runs of Perl, use the environment variable PERL_HASH_SEED,
503       see "PERL_HASH_SEED" in perlrun.  Using this restores the old (plat‐
504       form-specific) ordering: an even prettier solution might be to use the
505       "Sortkeys" filter of Data::Dumper.
506

AUTHOR

508       Gurusamy Sarathy        gsar@activestate.com
509
510       Copyright (c) 1996-98 Gurusamy Sarathy. All rights reserved.  This pro‐
511       gram is free software; you can redistribute it and/or modify it under
512       the same terms as Perl itself.
513

VERSION

515       Version 2.121  (Aug 24 2003)
516

SEE ALSO

518       perl(1)
519
520
521
522perl v5.8.8                       2001-09-21                 Data::Dumper(3pm)
Impressum