1Dumper(3) User Contributed Perl Documentation Dumper(3)
2
3
4
6 Data::Dumper - stringified perl data structures, suitable for both
7 printing and "eval"
8
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
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 content of each variable is output in a single Perl statement. Handles
36 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. (Please do consider the security
40 implications of eval'ing code from untrusted sources!)
41
42 Any references that are the same as one of those passed in will be
43 named $VARn (where n is a numeric suffix), and other duplicate
44 references to substructures within $VARn will be appropriately labeled
45 using arrow notation. You can specify names for individual values to
46 be dumped if you use the "Dump()" method, or you can change the default
47 $VAR prefix to something else. See $Data::Dumper::Varname and
48 $Data::Dumper::Terse below.
49
50 The default output of self-referential structures can be "eval"ed, but
51 the nested references to $VARn will be undefined, since a recursive
52 structure cannot be constructed using one Perl statement. You should
53 set the "Purity" flag to 1 to get additional statements that will
54 correctly fill in these references. Moreover, if "eval"ed when
55 strictures are in effect, you need to ensure that any variables it
56 accesses are previously declared.
57
58 In the extended usage form, the references to be dumped can be given
59 user-specified names. If a name begins with a "*", the output will
60 describe the dereferenced type of the supplied reference for hashes and
61 arrays, and coderefs. Output of names will be avoided where possible
62 if the "Terse" flag is set.
63
64 In many cases, methods that are used to set the internal state of the
65 object will return the object itself, so method calls can be
66 conveniently chained together.
67
68 Several styles of output are possible, all controlled by setting the
69 "Indent" flag. See "Configuration Variables or Methods" below for
70 details.
71
72 Methods
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
78 alphanumeric characters. You can begin a name with a "*" to
79 specify that the dereferenced type must be dumped instead of the
80 reference 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"),
95 subject 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
103 references. 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
106 useful 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 as a
116 list. When called with a reference to an array of replacement
117 values, returns the object itself. When called with any other type
118 of argument, dies.
119
120 $OBJ->Names([ARRAYREF])
121 Queries or replaces the internal array of user supplied names for
122 the values that will be dumped. When called without arguments,
123 returns the names. When called with an array of replacement names,
124 returns the object itself. If the number of replacment names
125 exceeds the number of values to be named, the excess names will not
126 be used. If the number of replacement names falls short of the
127 number of values to be named, the list of replacment names will be
128 exhausted and remaining values will not be renamed. When called
129 with any other type of argument, dies.
130
131 $OBJ->Reset
132 Clears the internal table of "seen" references and returns the
133 object itself.
134
135 Functions
136 Dumper(LIST)
137 Returns the stringified form of the values in the list, subject to
138 the configuration options below. The values will be named $VARn in
139 the output, where n is a numeric suffix. Will return a list of
140 strings in a list context.
141
142 Configuration Variables or Methods
143 Several configuration variables can be used to control the kind of
144 output generated when using the procedural interface. These variables
145 are usually "local"ized in a block so that other parts of the code are
146 not affected by the change.
147
148 These variables determine the default state of the object created by
149 calling the "new" method, but cannot be used to alter the state of the
150 object thereafter. The equivalent method names should be used instead
151 to query or set the internal state of the object.
152
153 The method forms return the object itself when called with arguments,
154 so that they can be chained together nicely.
155
156 · $Data::Dumper::Indent or $OBJ->Indent([NEWVAL])
157
158 Controls the style of indentation. It can be set to 0, 1, 2 or 3.
159 Style 0 spews output without any newlines, indentation, or spaces
160 between list items. It is the most compact format possible that
161 can still be called valid perl. Style 1 outputs a readable form
162 with newlines but no fancy indentation (each level in the structure
163 is simply indented by a fixed amount of whitespace). Style 2 (the
164 default) outputs a very readable form which takes into account the
165 length of hash keys (so the hash value lines up). Style 3 is like
166 style 2, but also annotates the elements of arrays with their index
167 (but the comment is on its own line, so array output consumes twice
168 the number of lines). Style 2 is the default.
169
170 · $Data::Dumper::Purity or $OBJ->Purity([NEWVAL])
171
172 Controls the degree to which the output can be "eval"ed to recreate
173 the supplied reference structures. Setting it to 1 will output
174 additional perl statements that will correctly recreate nested
175 references. The default is 0.
176
177 · $Data::Dumper::Pad or $OBJ->Pad([NEWVAL])
178
179 Specifies the string that will be prefixed to every line of the
180 output. Empty string by default.
181
182 · $Data::Dumper::Varname or $OBJ->Varname([NEWVAL])
183
184 Contains the prefix to use for tagging variable names in the
185 output. The default is "VAR".
186
187 · $Data::Dumper::Useqq or $OBJ->Useqq([NEWVAL])
188
189 When set, enables the use of double quotes for representing string
190 values. Whitespace other than space will be represented as
191 "[\n\t\r]", "unsafe" characters will be backslashed, and
192 unprintable characters will be output as quoted octal integers.
193 Since setting this variable imposes a performance penalty, the
194 default is 0. "Dump()" will run slower if this flag is set, since
195 the fast XSUB implementation doesn't support it yet.
196
197 · $Data::Dumper::Terse or $OBJ->Terse([NEWVAL])
198
199 When set, Data::Dumper will emit single, non-self-referential
200 values as atoms/terms rather than statements. This means that the
201 $VARn names will be avoided where possible, but be advised that
202 such output may not always be parseable by "eval".
203
204 · $Data::Dumper::Freezer or $OBJ->Freezer([NEWVAL])
205
206 Can be set to a method name, or to an empty string to disable the
207 feature. Data::Dumper will invoke that method via the object
208 before attempting to stringify it. This method can alter the
209 contents of the object (if, for instance, it contains data
210 allocated from C), and even rebless it in a different package. The
211 client is responsible for making sure the specified method can be
212 called via the object, and that the object ends up containing only
213 perl data types after the method has been called. Defaults to an
214 empty string.
215
216 If an object does not support the method specified (determined
217 using UNIVERSAL::can()) then the call will be skipped. If the
218 method dies a warning will be generated.
219
220 · $Data::Dumper::Toaster or $OBJ->Toaster([NEWVAL])
221
222 Can be set to a method name, or to an empty string to disable the
223 feature. Data::Dumper will emit a method call for any objects that
224 are to be dumped using the syntax "bless(DATA, CLASS)->METHOD()".
225 Note that this means that the method specified will have to perform
226 any modifications required on the object (like creating new state
227 within it, and/or reblessing it in a different package) and then
228 return it. The client is responsible for making sure the method
229 can be called via the object, and that it returns a valid object.
230 Defaults to an empty string.
231
232 · $Data::Dumper::Deepcopy or $OBJ->Deepcopy([NEWVAL])
233
234 Can be set to a boolean value to enable deep copies of structures.
235 Cross-referencing will then only be done when absolutely essential
236 (i.e., to break reference cycles). Default is 0.
237
238 · $Data::Dumper::Quotekeys or $OBJ->Quotekeys([NEWVAL])
239
240 Can be set to a boolean value to control whether hash keys are
241 quoted. A defined false value will avoid quoting hash keys when it
242 looks like a simple string. Default is 1, which will always
243 enclose hash keys in quotes.
244
245 · $Data::Dumper::Bless or $OBJ->Bless([NEWVAL])
246
247 Can be set to a string that specifies an alternative to the "bless"
248 builtin operator used to create objects. A function with the
249 specified name should exist, and should accept the same arguments
250 as the builtin. Default is "bless".
251
252 · $Data::Dumper::Pair or $OBJ->Pair([NEWVAL])
253
254 Can be set to a string that specifies the separator between hash
255 keys and values. To dump nested hash, array and scalar values to
256 JavaScript, use: "$Data::Dumper::Pair = ' : ';". Implementing
257 "bless" in JavaScript is left as an exercise for the reader. A
258 function with the specified name exists, and accepts the same
259 arguments as the builtin.
260
261 Default is: " => ".
262
263 · $Data::Dumper::Maxdepth or $OBJ->Maxdepth([NEWVAL])
264
265 Can be set to a positive integer that specifies the depth beyond
266 which we don't venture into a structure. Has no effect when
267 "Data::Dumper::Purity" is set. (Useful in debugger when we often
268 don't want to see more than enough). Default is 0, which means
269 there is no maximum depth.
270
271 · $Data::Dumper::Useperl or $OBJ->Useperl([NEWVAL])
272
273 Can be set to a boolean value which controls whether the pure Perl
274 implementation of "Data::Dumper" is used. The "Data::Dumper" module
275 is a dual implementation, with almost all functionality written in
276 both pure Perl and also in XS ('C'). Since the XS version is much
277 faster, it will always be used if possible. This option lets you
278 override the default behavior, usually for testing purposes only.
279 Default is 0, which means the XS implementation will be used if
280 possible.
281
282 · $Data::Dumper::Sortkeys or $OBJ->Sortkeys([NEWVAL])
283
284 Can be set to a boolean value to control whether hash keys are
285 dumped in sorted order. A true value will cause the keys of all
286 hashes to be dumped in Perl's default sort order. Can also be set
287 to a subroutine reference which will be called for each hash that
288 is dumped. In this case "Data::Dumper" will call the subroutine
289 once for each hash, passing it the reference of the hash. The
290 purpose of the subroutine is to return a reference to an array of
291 the keys that will be dumped, in the order that they should be
292 dumped. Using this feature, you can control both the order of the
293 keys, and which keys are actually used. In other words, this
294 subroutine acts as a filter by which you can exclude certain keys
295 from being dumped. Default is 0, which means that hash keys are not
296 sorted.
297
298 · $Data::Dumper::Deparse or $OBJ->Deparse([NEWVAL])
299
300 Can be set to a boolean value to control whether code references
301 are turned into perl source code. If set to a true value,
302 "B::Deparse" will be used to get the source of the code reference.
303 Using this option will force using the Perl implementation of the
304 dumper, since the fast XSUB implementation doesn't support it.
305
306 Caution : use this option only if you know that your coderefs will
307 be properly reconstructed by "B::Deparse".
308
309 · $Data::Dumper::Sparseseen or $OBJ->Sparseseen([NEWVAL])
310
311 By default, Data::Dumper builds up the "seen" hash of scalars that
312 it has encountered during serialization. This is very expensive.
313 This seen hash is necessary to support and even just detect
314 circular references. It is exposed to the user via the "Seen()"
315 call both for writing and reading.
316
317 If you, as a user, do not need explicit access to the "seen" hash,
318 then you can set the "Sparseseen" option to allow Data::Dumper to
319 eschew building the "seen" hash for scalars that are known not to
320 possess more than one reference. This speeds up serialization
321 considerably if you use the XS implementation.
322
323 Note: If you turn on "Sparseseen", then you must not rely on the
324 content of the seen hash since its contents will be an
325 implementation detail!
326
327 Exports
328 Dumper
329
331 Run these code snippets to get a quick feel for the behavior of this
332 module. When you are through with these examples, you may want to add
333 or change the various configuration variables described above, to see
334 their behavior. (See the testsuite in the Data::Dumper distribution
335 for more examples.)
336
337 use Data::Dumper;
338
339 package Foo;
340 sub new {bless {'a' => 1, 'b' => sub { return "foo" }}, $_[0]};
341
342 package Fuz; # a weird REF-REF-SCALAR object
343 sub new {bless \($_ = \ 'fu\'z'), $_[0]};
344
345 package main;
346 $foo = Foo->new;
347 $fuz = Fuz->new;
348 $boo = [ 1, [], "abcd", \*foo,
349 {1 => 'a', 023 => 'b', 0x45 => 'c'},
350 \\"p\q\'r", $foo, $fuz];
351
352 ########
353 # simple usage
354 ########
355
356 $bar = eval(Dumper($boo));
357 print($@) if $@;
358 print Dumper($boo), Dumper($bar); # pretty print (no array indices)
359
360 $Data::Dumper::Terse = 1; # don't output names where feasible
361 $Data::Dumper::Indent = 0; # turn off all pretty print
362 print Dumper($boo), "\n";
363
364 $Data::Dumper::Indent = 1; # mild pretty print
365 print Dumper($boo);
366
367 $Data::Dumper::Indent = 3; # pretty print with array indices
368 print Dumper($boo);
369
370 $Data::Dumper::Useqq = 1; # print strings in double quotes
371 print Dumper($boo);
372
373 $Data::Dumper::Pair = " : "; # specify hash key/value separator
374 print Dumper($boo);
375
376
377 ########
378 # recursive structures
379 ########
380
381 @c = ('c');
382 $c = \@c;
383 $b = {};
384 $a = [1, $b, $c];
385 $b->{a} = $a;
386 $b->{b} = $a->[1];
387 $b->{c} = $a->[2];
388 print Data::Dumper->Dump([$a,$b,$c], [qw(a b c)]);
389
390
391 $Data::Dumper::Purity = 1; # fill in the holes for eval
392 print Data::Dumper->Dump([$a, $b], [qw(*a b)]); # print as @a
393 print Data::Dumper->Dump([$b, $a], [qw(*b a)]); # print as %b
394
395
396 $Data::Dumper::Deepcopy = 1; # avoid cross-refs
397 print Data::Dumper->Dump([$b, $a], [qw(*b a)]);
398
399
400 $Data::Dumper::Purity = 0; # avoid cross-refs
401 print Data::Dumper->Dump([$b, $a], [qw(*b a)]);
402
403 ########
404 # deep structures
405 ########
406
407 $a = "pearl";
408 $b = [ $a ];
409 $c = { 'b' => $b };
410 $d = [ $c ];
411 $e = { 'd' => $d };
412 $f = { 'e' => $e };
413 print Data::Dumper->Dump([$f], [qw(f)]);
414
415 $Data::Dumper::Maxdepth = 3; # no deeper than 3 refs down
416 print Data::Dumper->Dump([$f], [qw(f)]);
417
418
419 ########
420 # object-oriented usage
421 ########
422
423 $d = Data::Dumper->new([$a,$b], [qw(a b)]);
424 $d->Seen({'*c' => $c}); # stash a ref without printing it
425 $d->Indent(3);
426 print $d->Dump;
427 $d->Reset->Purity(0); # empty the seen cache
428 print join "----\n", $d->Dump;
429
430
431 ########
432 # persistence
433 ########
434
435 package Foo;
436 sub new { bless { state => 'awake' }, shift }
437 sub Freeze {
438 my $s = shift;
439 print STDERR "preparing to sleep\n";
440 $s->{state} = 'asleep';
441 return bless $s, 'Foo::ZZZ';
442 }
443
444 package Foo::ZZZ;
445 sub Thaw {
446 my $s = shift;
447 print STDERR "waking up\n";
448 $s->{state} = 'awake';
449 return bless $s, 'Foo';
450 }
451
452 package main;
453 use Data::Dumper;
454 $a = Foo->new;
455 $b = Data::Dumper->new([$a], ['c']);
456 $b->Freezer('Freeze');
457 $b->Toaster('Thaw');
458 $c = $b->Dump;
459 print $c;
460 $d = eval $c;
461 print Data::Dumper->Dump([$d], ['d']);
462
463
464 ########
465 # symbol substitution (useful for recreating CODE refs)
466 ########
467
468 sub foo { print "foo speaking\n" }
469 *other = \&foo;
470 $bar = [ \&other ];
471 $d = Data::Dumper->new([\&other,$bar],['*other','bar']);
472 $d->Seen({ '*foo' => \&foo });
473 print $d->Dump;
474
475
476 ########
477 # sorting and filtering hash keys
478 ########
479
480 $Data::Dumper::Sortkeys = \&my_filter;
481 my $foo = { map { (ord, "$_$_$_") } 'I'..'Q' };
482 my $bar = { %$foo };
483 my $baz = { reverse %$foo };
484 print Dumper [ $foo, $bar, $baz ];
485
486 sub my_filter {
487 my ($hash) = @_;
488 # return an array ref containing the hash keys to dump
489 # in the order that you want them to be dumped
490 return [
491 # Sort the keys of %$foo in reverse numeric order
492 $hash eq $foo ? (sort {$b <=> $a} keys %$hash) :
493 # Only dump the odd number keys of %$bar
494 $hash eq $bar ? (grep {$_ % 2} keys %$hash) :
495 # Sort keys in default order for all other hashes
496 (sort keys %$hash)
497 ];
498 }
499
501 Due to limitations of Perl subroutine call semantics, you cannot pass
502 an array or hash. Prepend it with a "\" to pass its reference instead.
503 This will be remedied in time, now that Perl has subroutine prototypes.
504 For now, you need to use the extended usage form, and prepend the name
505 with a "*" to output it as a hash or array.
506
507 "Data::Dumper" cheats with CODE references. If a code reference is
508 encountered in the structure being processed (and if you haven't set
509 the "Deparse" flag), an anonymous subroutine that contains the string
510 '"DUMMY"' will be inserted in its place, and a warning will be printed
511 if "Purity" is set. You can "eval" the result, but bear in mind that
512 the anonymous sub that gets created is just a placeholder. Someday,
513 perl will have a switch to cache-on-demand the string representation of
514 a compiled piece of code, I hope. If you have prior knowledge of all
515 the code refs that your data structures are likely to have, you can use
516 the "Seen" method to pre-seed the internal reference table and make the
517 dumped output point to them, instead. See "EXAMPLES" above.
518
519 The "Useqq" and "Deparse" flags makes Dump() run slower, since the XSUB
520 implementation does not support them.
521
522 SCALAR objects have the weirdest looking "bless" workaround.
523
524 Pure Perl version of "Data::Dumper" escapes UTF-8 strings correctly
525 only in Perl 5.8.0 and later.
526
527 NOTE
528 Starting from Perl 5.8.1 different runs of Perl will have different
529 ordering of hash keys. The change was done for greater security, see
530 "Algorithmic Complexity Attacks" in perlsec. This means that different
531 runs of Perl will have different Data::Dumper outputs if the data
532 contains hashes. If you need to have identical Data::Dumper outputs
533 from different runs of Perl, use the environment variable
534 PERL_HASH_SEED, see "PERL_HASH_SEED" in perlrun. Using this restores
535 the old (platform-specific) ordering: an even prettier solution might
536 be to use the "Sortkeys" filter of Data::Dumper.
537
539 Gurusamy Sarathy gsar@activestate.com
540
541 Copyright (c) 1996-98 Gurusamy Sarathy. All rights reserved. This
542 program is free software; you can redistribute it and/or modify it
543 under the same terms as Perl itself.
544
546 Version 2.145 (March 15 2013))
547
549 perl(1)
550
551
552
553perl v5.16.3 2013-03-15 Dumper(3)