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 replacement 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 replacement 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 lines up the hash keys.
165 Style 3 is like style 2, but also annotates the elements of arrays
166 with their index (but the comment is on its own line, so array
167 output consumes twice the number of lines). Style 2 is the
168 default.
169
170 • $Data::Dumper::Trailingcomma or $OBJ->Trailingcomma([NEWVAL])
171
172 Controls whether a comma is added after the last element of an
173 array or hash. Even when true, no comma is added between the last
174 element of an array or hash and a closing bracket when they appear
175 on the same line. The default is false.
176
177 • $Data::Dumper::Purity or $OBJ->Purity([NEWVAL])
178
179 Controls the degree to which the output can be "eval"ed to recreate
180 the supplied reference structures. Setting it to 1 will output
181 additional perl statements that will correctly recreate nested
182 references. The default is 0.
183
184 • $Data::Dumper::Pad or $OBJ->Pad([NEWVAL])
185
186 Specifies the string that will be prefixed to every line of the
187 output. Empty string by default.
188
189 • $Data::Dumper::Varname or $OBJ->Varname([NEWVAL])
190
191 Contains the prefix to use for tagging variable names in the
192 output. The default is "VAR".
193
194 • $Data::Dumper::Useqq or $OBJ->Useqq([NEWVAL])
195
196 When set, enables the use of double quotes for representing string
197 values. Whitespace other than space will be represented as
198 "[\n\t\r]", "unsafe" characters will be backslashed, and
199 unprintable characters will be output as quoted octal integers.
200 The default is 0.
201
202 • $Data::Dumper::Terse or $OBJ->Terse([NEWVAL])
203
204 When set, Data::Dumper will emit single, non-self-referential
205 values as atoms/terms rather than statements. This means that the
206 $VARn names will be avoided where possible, but be advised that
207 such output may not always be parseable by "eval".
208
209 • $Data::Dumper::Freezer or $OBJ->Freezer([NEWVAL])
210
211 Can be set to a method name, or to an empty string to disable the
212 feature. Data::Dumper will invoke that method via the object
213 before attempting to stringify it. This method can alter the
214 contents of the object (if, for instance, it contains data
215 allocated from C), and even rebless it in a different package. The
216 client is responsible for making sure the specified method can be
217 called via the object, and that the object ends up containing only
218 perl data types after the method has been called. Defaults to an
219 empty string.
220
221 If an object does not support the method specified (determined
222 using UNIVERSAL::can()) then the call will be skipped. If the
223 method dies a warning will be generated.
224
225 • $Data::Dumper::Toaster or $OBJ->Toaster([NEWVAL])
226
227 Can be set to a method name, or to an empty string to disable the
228 feature. Data::Dumper will emit a method call for any objects that
229 are to be dumped using the syntax "bless(DATA, CLASS)->METHOD()".
230 Note that this means that the method specified will have to perform
231 any modifications required on the object (like creating new state
232 within it, and/or reblessing it in a different package) and then
233 return it. The client is responsible for making sure the method
234 can be called via the object, and that it returns a valid object.
235 Defaults to an empty string.
236
237 • $Data::Dumper::Deepcopy or $OBJ->Deepcopy([NEWVAL])
238
239 Can be set to a boolean value to enable deep copies of structures.
240 Cross-referencing will then only be done when absolutely essential
241 (i.e., to break reference cycles). Default is 0.
242
243 • $Data::Dumper::Quotekeys or $OBJ->Quotekeys([NEWVAL])
244
245 Can be set to a boolean value to control whether hash keys are
246 quoted. A defined false value will avoid quoting hash keys when it
247 looks like a simple string. Default is 1, which will always
248 enclose hash keys in quotes.
249
250 • $Data::Dumper::Bless or $OBJ->Bless([NEWVAL])
251
252 Can be set to a string that specifies an alternative to the "bless"
253 builtin operator used to create objects. A function with the
254 specified name should exist, and should accept the same arguments
255 as the builtin. Default is "bless".
256
257 • $Data::Dumper::Pair or $OBJ->Pair([NEWVAL])
258
259 Can be set to a string that specifies the separator between hash
260 keys and values. To dump nested hash, array and scalar values to
261 JavaScript, use: "$Data::Dumper::Pair = ' : ';". Implementing
262 "bless" in JavaScript is left as an exercise for the reader. A
263 function with the specified name exists, and accepts the same
264 arguments as the builtin.
265
266 Default is: " => ".
267
268 • $Data::Dumper::Maxdepth or $OBJ->Maxdepth([NEWVAL])
269
270 Can be set to a positive integer that specifies the depth beyond
271 which we don't venture into a structure. Has no effect when
272 "Data::Dumper::Purity" is set. (Useful in debugger when we often
273 don't want to see more than enough). Default is 0, which means
274 there is no maximum depth.
275
276 • $Data::Dumper::Maxrecurse or $OBJ->Maxrecurse([NEWVAL])
277
278 Can be set to a positive integer that specifies the depth beyond
279 which recursion into a structure will throw an exception. This is
280 intended as a security measure to prevent perl running out of stack
281 space when dumping an excessively deep structure. Can be set to 0
282 to remove the limit. Default is 1000.
283
284 • $Data::Dumper::Useperl or $OBJ->Useperl([NEWVAL])
285
286 Can be set to a boolean value which controls whether the pure Perl
287 implementation of "Data::Dumper" is used. The "Data::Dumper" module
288 is a dual implementation, with almost all functionality written in
289 both pure Perl and also in XS ('C'). Since the XS version is much
290 faster, it will always be used if possible. This option lets you
291 override the default behavior, usually for testing purposes only.
292 Default is 0, which means the XS implementation will be used if
293 possible.
294
295 • $Data::Dumper::Sortkeys or $OBJ->Sortkeys([NEWVAL])
296
297 Can be set to a boolean value to control whether hash keys are
298 dumped in sorted order. A true value will cause the keys of all
299 hashes to be dumped in Perl's default sort order. Can also be set
300 to a subroutine reference which will be called for each hash that
301 is dumped. In this case "Data::Dumper" will call the subroutine
302 once for each hash, passing it the reference of the hash. The
303 purpose of the subroutine is to return a reference to an array of
304 the keys that will be dumped, in the order that they should be
305 dumped. Using this feature, you can control both the order of the
306 keys, and which keys are actually used. In other words, this
307 subroutine acts as a filter by which you can exclude certain keys
308 from being dumped. Default is 0, which means that hash keys are not
309 sorted.
310
311 • $Data::Dumper::Deparse or $OBJ->Deparse([NEWVAL])
312
313 Can be set to a boolean value to control whether code references
314 are turned into perl source code. If set to a true value,
315 "B::Deparse" will be used to get the source of the code reference.
316 In older versions, using this option imposed a significant
317 performance penalty when dumping parts of a data structure other
318 than code references, but that is no longer the case.
319
320 Caution : use this option only if you know that your coderefs will
321 be properly reconstructed by "B::Deparse".
322
323 • $Data::Dumper::Sparseseen or $OBJ->Sparseseen([NEWVAL])
324
325 By default, Data::Dumper builds up the "seen" hash of scalars that
326 it has encountered during serialization. This is very expensive.
327 This seen hash is necessary to support and even just detect
328 circular references. It is exposed to the user via the "Seen()"
329 call both for writing and reading.
330
331 If you, as a user, do not need explicit access to the "seen" hash,
332 then you can set the "Sparseseen" option to allow Data::Dumper to
333 eschew building the "seen" hash for scalars that are known not to
334 possess more than one reference. This speeds up serialization
335 considerably if you use the XS implementation.
336
337 Note: If you turn on "Sparseseen", then you must not rely on the
338 content of the seen hash since its contents will be an
339 implementation detail!
340
341 Exports
342 Dumper
343
345 Run these code snippets to get a quick feel for the behavior of this
346 module. When you are through with these examples, you may want to add
347 or change the various configuration variables described above, to see
348 their behavior. (See the testsuite in the Data::Dumper distribution
349 for more examples.)
350
351 use Data::Dumper;
352
353 package Foo;
354 sub new {bless {'a' => 1, 'b' => sub { return "foo" }}, $_[0]};
355
356 package Fuz; # a weird REF-REF-SCALAR object
357 sub new {bless \($_ = \ 'fu\'z'), $_[0]};
358
359 package main;
360 $foo = Foo->new;
361 $fuz = Fuz->new;
362 $boo = [ 1, [], "abcd", \*foo,
363 {1 => 'a', 023 => 'b', 0x45 => 'c'},
364 \\"p\q\'r", $foo, $fuz];
365
366 ########
367 # simple usage
368 ########
369
370 $bar = eval(Dumper($boo));
371 print($@) if $@;
372 print Dumper($boo), Dumper($bar); # pretty print (no array indices)
373
374 $Data::Dumper::Terse = 1; # don't output names where feasible
375 $Data::Dumper::Indent = 0; # turn off all pretty print
376 print Dumper($boo), "\n";
377
378 $Data::Dumper::Indent = 1; # mild pretty print
379 print Dumper($boo);
380
381 $Data::Dumper::Indent = 3; # pretty print with array indices
382 print Dumper($boo);
383
384 $Data::Dumper::Useqq = 1; # print strings in double quotes
385 print Dumper($boo);
386
387 $Data::Dumper::Pair = " : "; # specify hash key/value separator
388 print Dumper($boo);
389
390
391 ########
392 # recursive structures
393 ########
394
395 @c = ('c');
396 $c = \@c;
397 $b = {};
398 $a = [1, $b, $c];
399 $b->{a} = $a;
400 $b->{b} = $a->[1];
401 $b->{c} = $a->[2];
402 print Data::Dumper->Dump([$a,$b,$c], [qw(a b c)]);
403
404
405 $Data::Dumper::Purity = 1; # fill in the holes for eval
406 print Data::Dumper->Dump([$a, $b], [qw(*a b)]); # print as @a
407 print Data::Dumper->Dump([$b, $a], [qw(*b a)]); # print as %b
408
409
410 $Data::Dumper::Deepcopy = 1; # avoid cross-refs
411 print Data::Dumper->Dump([$b, $a], [qw(*b a)]);
412
413
414 $Data::Dumper::Purity = 0; # avoid cross-refs
415 print Data::Dumper->Dump([$b, $a], [qw(*b a)]);
416
417 ########
418 # deep structures
419 ########
420
421 $a = "pearl";
422 $b = [ $a ];
423 $c = { 'b' => $b };
424 $d = [ $c ];
425 $e = { 'd' => $d };
426 $f = { 'e' => $e };
427 print Data::Dumper->Dump([$f], [qw(f)]);
428
429 $Data::Dumper::Maxdepth = 3; # no deeper than 3 refs down
430 print Data::Dumper->Dump([$f], [qw(f)]);
431
432
433 ########
434 # object-oriented usage
435 ########
436
437 $d = Data::Dumper->new([$a,$b], [qw(a b)]);
438 $d->Seen({'*c' => $c}); # stash a ref without printing it
439 $d->Indent(3);
440 print $d->Dump;
441 $d->Reset->Purity(0); # empty the seen cache
442 print join "----\n", $d->Dump;
443
444
445 ########
446 # persistence
447 ########
448
449 package Foo;
450 sub new { bless { state => 'awake' }, shift }
451 sub Freeze {
452 my $s = shift;
453 print STDERR "preparing to sleep\n";
454 $s->{state} = 'asleep';
455 return bless $s, 'Foo::ZZZ';
456 }
457
458 package Foo::ZZZ;
459 sub Thaw {
460 my $s = shift;
461 print STDERR "waking up\n";
462 $s->{state} = 'awake';
463 return bless $s, 'Foo';
464 }
465
466 package main;
467 use Data::Dumper;
468 $a = Foo->new;
469 $b = Data::Dumper->new([$a], ['c']);
470 $b->Freezer('Freeze');
471 $b->Toaster('Thaw');
472 $c = $b->Dump;
473 print $c;
474 $d = eval $c;
475 print Data::Dumper->Dump([$d], ['d']);
476
477
478 ########
479 # symbol substitution (useful for recreating CODE refs)
480 ########
481
482 sub foo { print "foo speaking\n" }
483 *other = \&foo;
484 $bar = [ \&other ];
485 $d = Data::Dumper->new([\&other,$bar],['*other','bar']);
486 $d->Seen({ '*foo' => \&foo });
487 print $d->Dump;
488
489
490 ########
491 # sorting and filtering hash keys
492 ########
493
494 $Data::Dumper::Sortkeys = \&my_filter;
495 my $foo = { map { (ord, "$_$_$_") } 'I'..'Q' };
496 my $bar = { %$foo };
497 my $baz = { reverse %$foo };
498 print Dumper [ $foo, $bar, $baz ];
499
500 sub my_filter {
501 my ($hash) = @_;
502 # return an array ref containing the hash keys to dump
503 # in the order that you want them to be dumped
504 return [
505 # Sort the keys of %$foo in reverse numeric order
506 $hash eq $foo ? (sort {$b <=> $a} keys %$hash) :
507 # Only dump the odd number keys of %$bar
508 $hash eq $bar ? (grep {$_ % 2} keys %$hash) :
509 # Sort keys in default order for all other hashes
510 (sort keys %$hash)
511 ];
512 }
513
515 Due to limitations of Perl subroutine call semantics, you cannot pass
516 an array or hash. Prepend it with a "\" to pass its reference instead.
517 This will be remedied in time, now that Perl has subroutine prototypes.
518 For now, you need to use the extended usage form, and prepend the name
519 with a "*" to output it as a hash or array.
520
521 "Data::Dumper" cheats with CODE references. If a code reference is
522 encountered in the structure being processed (and if you haven't set
523 the "Deparse" flag), an anonymous subroutine that contains the string
524 '"DUMMY"' will be inserted in its place, and a warning will be printed
525 if "Purity" is set. You can "eval" the result, but bear in mind that
526 the anonymous sub that gets created is just a placeholder. Even using
527 the "Deparse" flag will in some cases produce results that behave
528 differently after being passed to "eval"; see the documentation for
529 B::Deparse.
530
531 SCALAR objects have the weirdest looking "bless" workaround.
532
533 NOTE
534 Different runs of Perl will have different ordering of hash keys. The
535 change was done for greater security, see "Algorithmic Complexity
536 Attacks" in perlsec. This means that different runs of Perl will have
537 different Data::Dumper outputs if the data contains hashes. If you
538 need to have identical Data::Dumper outputs from different runs of
539 Perl, use the environment variable PERL_HASH_SEED, see "PERL_HASH_SEED"
540 in perlrun. Using this restores the old (platform-specific) ordering:
541 an even prettier solution might be to use the "Sortkeys" filter of
542 Data::Dumper.
543
545 Gurusamy Sarathy gsar@activestate.com
546
547 Copyright (c) 1996-2019 Gurusamy Sarathy. All rights reserved. This
548 program is free software; you can redistribute it and/or modify it
549 under the same terms as Perl itself.
550
552 Version 2.184
553
555 perl(1)
556
557
558
559perl v5.36.0 2022-07-22 Dumper(3)