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

EXAMPLES

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

BUGS

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

AUTHOR

512       Gurusamy Sarathy        gsar@activestate.com
513
514       Copyright (c) 1996-98 Gurusamy Sarathy. All rights reserved.  This
515       program is free software; you can redistribute it and/or modify it
516       under the same terms as Perl itself.
517

VERSION

519       Version 2.124  (Jun 13 2009)
520

SEE ALSO

522       perl(1)
523
524
525
526perl v5.10.1                      2009-06-23                 Data::Dumper(3pm)
Impressum