Data::Dumper(3perl)
๐ Data::Dumper ๐
from the Perl Programmers Reference Guide โ Data::Dumper(3perl)
โจ NAME โจ
Data::Dumper โ stringified perl data structures, suitable for both printing and "eval" ๐
๐ SYNOPSIS ๐
okay so here's how you use this thing, bestie:
use Data::Dumper;
# simple procedural interface
print Dumper($foo, $bar);
# extended usage with names
print Data::Dumper->Dump([$foo, $bar], [qw(foo *ary)]);
# configuration variables
{
local $Data::Dumper::Purity = 1;
eval Data::Dumper->Dump([$foo, $bar], [qw(foo *ary)]);
}
# OO usage
my $d = Data::Dumper->new([$foo, $bar], [qw(foo *ary)]);
...
print $d->Dump;
...
$d->Purity(1)->Terse(1)->Deepcopy(1);
eval $d->Dump;
๐ DESCRIPTION ๐
So bestie, you give Data::Dumper a list of scalars or reference variables, and it writes out what's inside them in perl syntax. And yes, the references can be objects too! Each variable's content gets output in a single Perl statement. And it handles self-referential structures correctly โ like it knows how to deal with loops and stuff, no cap. ๐
The return value can be "eval"ed to get back an identical copy of the original reference structure.
๐จ WARNING: Please do consider the security implications of eval'ing code from untrusted sources! Like, seriously, don't do that. ๐จ
Any references that are the same as one of those passed in will be named $VARn (where n is a numeric suffix), and other duplicate references to substructures within $VARn will be appropriately labeled using arrow notation. You can specify names for individual values to be dumped if you use the Dump() method, or you can change the default $VAR prefix to something else. See $Data::Dumper::Varname and $Data::Dumper::Terse in "Configuration Variables or Methods" below.
The default output of self-referential structures can be "eval"ed, but the nested references to $VARn will be undefined, since a recursive structure cannot be constructed using one Perl statement. You should set the "Purity" flag to 1 to get additional statements that will correctly fill in these references. Moreover, if "eval"ed when strictures are in effect, you need to ensure that any variables it accesses are previously declared.
In the extended usage form, the references to be dumped can be given user-specified names. If a name begins with a "*", the output will describe the dereferenced type of the supplied reference for hashes and arrays, and coderefs. Output of names will be avoided where possible if the "Terse" flag is set.
In many cases, methods that are used to set the internal state of the object will return the object itself, so method calls can be conveniently chained together.
Several styles of output are possible, all controlled by setting the "Indent" flag. See "Configuration Variables or Methods" below for details.
๐ฆ Methods ๐ฆ
PACKAGE->new(ARRAYREF [, ARRAYREF])โ Returns a newly createdData::Dumperobject, slay. The first argument is an anonymous array of values to be dumped. The optional second argument is an anonymous array of names for the values. The names need not have a leading$sign, and must be composed of alphanumeric characters. You can begin a name with a*to specify that the dereferenced type must be dumped instead of the reference itself, for ARRAY and HASH references.
The prefix specified by $Data::Dumper::Varname will be used with a numeric suffix if the name for a value is undefined.
Data::Dumper will catalog all references encountered while dumping the values. Cross-references (in the form of names of substructures in perl syntax) will be inserted at all possible points, preserving any structural interdependencies in the original set of values. Structure traversal is depth-first, and proceeds in order from the first supplied value to the last.
$OBJ->DumporPACKAGE->Dump(ARRAYREF [, ARRAYREF])โ Returns the stringified form of the values stored in the object (preserving the order in which they were supplied tonew), subject to the configuration options below. In a list context, it returns a list of strings corresponding to the supplied values.
The second form, for convenience, simply calls the new method on its arguments before dumping the object immediately. So you can just do it all in one go, bestie. ๐ซ
$OBJ->Seen([HASHREF])โ Queries or adds to the internal table of already encountered references. You must useResetto explicitly clear the table if needed. Such references are not dumped; instead, their names are inserted wherever they are encountered subsequently. This is useful especially for properly dumping subroutine references.
Expects an anonymous hash of name => value pairs. Same rules apply for names as in new. If no argument is supplied, will return the seen list of name => value pairs, in a list context. Otherwise, returns the object itself.
$OBJ->Values([ARRAYREF])โ Queries or replaces the internal array of values that will be dumped. When called without arguments, returns the values as a list. When called with a reference to an array of replacement values, returns the object itself. When called with any other type of argument, dies. So don't try it. ๐$OBJ->Names([ARRAYREF])โ Queries or replaces the internal array of user supplied names for the values that will be dumped. When called without arguments, returns the names. When called with an array of replacement names, returns the object itself. If the number of replacement names exceeds the number of values to be named, the excess names will not be used. If the number of replacement names falls short of the number of values to be named, the list of replacement names will be exhausted and remaining values will not be renamed. When called with any other type of argument, dies. So yeah, be careful. ๐$OBJ->Resetโ Clears the internal table ofseenreferences and returns the object itself. So fresh start, iconic. โจ
๐ Functions ๐
Dumper(LIST)โ Returns the stringified form of the values in the list, subject to the configuration options below. The values will be named$VARnin the output, wherenis a numeric suffix. Will return a list of strings in a list context. So you can just call it and get your string, bestie. โจ
๐ Configuration Variables or Methods ๐
Okay so there are a bunch of config variables and methods that control the output vibe when you use the procedural interface. These variables are usually localized in a block so that other parts of the code are not affected by the change. No cap.
These variables determine the default state of the object created by calling the new method, but cannot be used to alter the state of the object thereafter. The equivalent method names should be used instead to query or set the internal state of the object.
The method forms return the object itself when called with arguments, so that they can be chained together nicely. It's giving fluent interface, periodt.
$Data::Dumper::Indentor$OBJ->Indent([NEWVAL])โ Controls the style of indentation. It can be set to0,1,2or3. Style0spews output without any newlines, indentation, or spaces between list items. It is the most compact format possible that can still be called valid perl. Style1outputs a readable form with newlines but no fancy indentation (each level in the structure is simply indented by a fixed amount of whitespace). Style2(the default) outputs a very readable form which lines up the hash keys. Style3is like style2, but also annotates the elements of arrays with their index (but the comment is on its own line, so array output consumes twice the number of lines). Style2is the default. So yeah, pick your vibe. ๐$Data::Dumper::Trailingcommaor$OBJ->Trailingcomma([NEWVAL])โ Controls whether a comma is added after the last element of an array or hash. Even when true, no comma is added between the last element of an array or hash and a closing bracket when they appear on the same line. The default is false. So it's off by default, bestie.$Data::Dumper::Purityor$OBJ->Purity([NEWVAL])โ Controls the degree to which the output can be"eval"ed to recreate the supplied reference structures. Setting it to1will output additional perl statements that will correctly recreate nested references. The default is0. So if you need those nested refs, turn it on. ๐ฅ$Data::Dumper::Pador$OBJ->Pad([NEWVAL])โ Specifies the string that will be prefixed to every line of the output. Empty string by default. So you can add some flair to every line if you want. โจ$Data::Dumper::Varnameor$OBJ->Varname([NEWVAL])โ Contains the prefix to use for tagging variable names in the output. The default is"VAR". So your variables will be like$VAR1,$VAR2, etc. ๐$Data::Dumper::Useqqor$OBJ->Useqq([NEWVAL])โ When set, enables the use of double quotes for representing string values. Whitespace other than space will be represented as"[\n\t\r]","unsafe"characters will be backslashed, and unprintable characters will be output as quoted octal integers. The default is0. So it's off by default, but it makes things pretty. ๐ธ$Data::Dumper::Terseor$OBJ->Terse([NEWVAL])โ When set, Data::Dumper will emit single, non-self-referential values as atoms/terms rather than statements. This means that the$VARnnames will be avoided where possible, but be advised that such output may not always be parseable by"eval". So use with caution, bestie. ๐ญ$Data::Dumper::Freezeror$OBJ->Freezer([NEWVAL])โ Can be set to a method name, or to an empty string to disable the feature. Data::Dumper will invoke that method via the object before attempting to stringify it. This method can alter the contents of the object (if, for instance, it contains data allocated from C), and even rebless it in a different package. The client is responsible for making sure the specified method can be called via the object, and that the object ends up containing only perl data types after the method has been called. Defaults to an empty string.
If an object does not support the method specified (determined using UNIVERSAL::can()) then the call will be skipped. If the method dies a warning will be generated. So yeah, it's a whole thing. ๐ง
$Data::Dumper::Toasteror$OBJ->Toaster([NEWVAL])โ Can be set to a method name, or to an empty string to disable the feature. Data::Dumper will emit a method call for any objects that are to be dumped using the syntax"bless(DATA, CLASS)->METHOD()". Note that this means that the method specified will have to perform any modifications required on the object (like creating new state within it, and/or reblessing it in a different package) and then return it. The client is responsible for making sure the method can be called via the object, and that it returns a valid object. Defaults to an empty string. So it's like a toaster, but for objects. ๐$Data::Dumper::Deepcopyor$OBJ->Deepcopy([NEWVAL])$Data::Dumper::Deepcopyor$OBJ->Deepcopy([NEWVAL])โ set it to a boolean and it'll do a deep copy of your structures, bestie ๐. Cross-referencing only kicks in when it's absolutely gotta happen (aka breaking reference cycles). Default is0.$Data::Dumper::Quotekeysor$OBJ->Quotekeys([NEWVAL])โ boolean, controls whether hash keys get quoted ๐. Set it to a defined false value and it'll skip the quotes when a key looks like a simple string. Default is1, which means every hash key gets wrapped in quotes, always, no exceptions, periodt.$Data::Dumper::Blessor$OBJ->Bless([NEWVAL])โ set it to a string naming an alternative to theblessbuiltin operator used to create objects ๐ฆ. A function with that name has to actually exist, and it needs to accept the same arguments as the builtin. Default isbless.$Data::Dumper::Pairor$OBJ->Pair([NEWVAL])โ a string that sets the separator between hash keys and values โจ. Wanna dump nested hash, array and scalar values to JavaScript? Then do:$Data::Dumper::Pair = ' : ';. Implementingblessin JavaScript is left as an exercise for the reader ๐. A function with the specified name exists, and accepts the same arguments as the builtin.
Default is: " => ".
$Data::Dumper::Maxdepthor$OBJ->Maxdepth([NEWVAL])โ a positive integer that sets the depth past which we simply do not venture into a structure ๐ซ๐ณ๏ธ. Has no effect whenData::Dumper::Purityis set. (Super useful in the debugger, where you often don't wanna see more than enough.) Default is0, which means no maximum depth at all.$Data::Dumper::Maxrecurseor$OBJ->Maxrecurse([NEWVAL])โ a positive integer that sets the depth past which recursing into a structure will throw an exception ๐ญ. It's a security measure, fr โ it stops perl from running out of stack space when dumping an absurdly deep structure. Set it to0to remove the limit. Default is1000.$Data::Dumper::Useperlor$OBJ->Useperl([NEWVAL])โ a boolean that controls whether the pure Perl implementation ofData::Dumpergets used ๐. TheData::Dumpermodule is a dual implementation, with almost all the functionality written in both pure Perl and in XS ('C'). Since the XS version is way faster, it always gets used if possible. This option lets you override the default behavior โ usually for testing purposes only, iykyk. Default is0, which means the XS implementation will be used if possible.$Data::Dumper::Sortkeysor$OBJ->Sortkeys([NEWVAL])โ a boolean that controls whether hash keys get dumped in sorted order ๐ค. A true value makes the keys of all hashes dump in Perl's default sort order. You can also set it to a subroutine reference, which gets called for every hash that gets dumped. In that caseData::Dumpercalls your sub once per hash and passes it the reference of the hash. The sub's whole job is to return a reference to an array of the keys that will be dumped, in the order they should be dumped. Using this, you control both the order of the keys and which keys actually get used โ in other words, the sub acts as a filter you can use to exclude certain keys from being dumped ๐ง. Default is0, which means hash keys are not sorted.$Data::Dumper::Deparseor$OBJ->Deparse([NEWVAL])โ a boolean that controls whether code references get turned into perl source code ๐. If it's true,B::Deparseis used to grab the source of the code reference. In older versions, turning this on came with a significant performance penalty when dumping parts of a data structure other than code references โ but that's no longer the case, we ate ๐ .
Caution: use this option only if you know that your coderefs will be properly reconstructed by B::Deparse.
$Data::Dumper::Sparseseenor$OBJ->Sparseseen([NEWVAL])โ okay so by default, Data::Dumper builds up theseenhash of scalars it's encountered during serialization. That is very expensive, ngl ๐ฎ๐จ. This seen hash is necessary to support and even just detect circular references. It's exposed to you via theSeen()call, for both writing and reading.
If you, as a user, don't need explicit access to the seen hash, then you can set the Sparseseen option to let Data::Dumper eschew building the seen hash for scalars that are known not to possess more than one reference. This speeds up serialization considerably if you use the XS implementation ๐๏ธ.
Note: If you turn on Sparseseen, then you must not rely on the content of the seen hash, since its contents will be an implementation detail!
โจ Exports โจ
Dumper
๐ EXAMPLES ๐
Run these code snippets to get a quick feel for how this module behaves, bestie. When you're through with these examples, you may wanna add or change the various configuration variables described above to see how they behave. (See the testsuite in the Data::Dumper distribution for more examples ๐ซถ.)
use Data::Dumper;
package Foo;
sub new {bless {'a' => 1, 'b' => sub { return "foo" }}, $_[0]};
package Fuz; # a weird REF-REF-SCALAR object
sub new {bless \($_ = \ 'fu\'z'), $_[0]};
package main;
$foo = Foo->new;
$fuz = Fuz->new;
$boo = [ 1, [], "abcd", \*foo,
{1 => 'a', 023 => 'b', 0x45 => 'c'},
\\"p\q\'r", $foo, $fuz];
########
# simple usage
########
$bar = eval(Dumper($boo));
print($@) if $@;
print Dumper($boo), Dumper($bar); # pretty print (no array indices)
$Data::Dumper::Terse = 1; # don't output names where feasible
$Data::Dumper::Indent = 0; # turn off all pretty print
print Dumper($boo), "\n";
$Data::Dumper::Indent = 1; # mild pretty print
print Dumper($boo);
$Data::Dumper::Indent = 3; # pretty print with array indices
print Dumper($boo);
$Data::Dumper::Useqq = 1; # print strings in double quotes
print Dumper($boo);
$Data::Dumper::Pair = " : "; # specify hash key/value separator
print Dumper($boo);
########
# recursive structures
########
@c = ('c');
$c = \@c;
$b = {};
$a = [1, $b, $c];
$b->{a} = $a;
$b->{b} = $a->[1];
$b->{c} = $a->[2];
print Data::Dumper->Dump([$a,$b,$c], [qw(a b c)]);
$Data::Dumper::Purity = 1; # fill in the holes for eval
print Data::Dumper->Dump([$a, $b], [qw(*a b)]); # print as @a
print Data::Dumper->Dump([$b, $a], [qw(*b a)]); # print as %b
$Data::Dumper::Deepcopy = 1; # avoid cross-refs
print Data::Dumper->Dump([$b, $a], [qw(*b a)]);
$Data::Dumper::Purity = 0; # avoid cross-refs
print Data::Dumper->Dump([$b, $a], [qw(*b a)]);
########
# deep structures
########
$a = "pearl";
$b = [ $a ];
$c = { 'b' => $b };
$d = [ $c ];
$e = { 'd' => $d };
$f = { 'e' => $e };
print Data::Dumper->Dump([$f], [qw(f)]);
$Data::Dumper::Maxdepth = 3; # no deeper than 3 refs down
print Data::Dumper->Dump([$f], [qw(f)]);
########
# object-oriented usage
########
$d = Data::Dumper->new([$a,$b], [qw(a b)]);
$d->Seen({'*c' => $c}); # stash a ref without printing it
$d->Indent(3);
print $d->Dump;
$d->Reset->Purity(0); # empty the seen cache
print join "----\n", $d->Dump;
########
# persistence
########
package Foo;
sub new { bless { state => 'awake' }, shift }
sub Freeze {
my $s = shift;
print STDERR "preparing to sleep\n";
$s->{state} = 'asleep';
return bless $s, 'Foo::ZZZ';
}
package Foo::ZZZ;
sub Thaw {
my $s = shift;
print STDERR "waking up\n";
$s->{state} = 'awake';
return bless $s, 'Foo';
}
package main;
use Data::Dumper;
$a = Foo->new;
$b = Data::Dumper->new([$a], ['c']);
$b->Freezer('Freeze');
$b->Toaster('Thaw');
$c = $b->Dump;
print $c;
$d = eval $c;
print Data::Dumper->Dump([$d], ['d']);
########
# symbol substitution (useful for recreating CODE refs)
########
sub foo { print "foo speaking\n" }
*other = \&foo;
$bar = [ \&other ];
$d = Data::Dumper->new([\&other,$bar],['*other','bar']);
$d->Seen({ '*foo' => \&foo });
print $d->Dump;
########
# sorting and filtering hash keys
########
$Data::Dumper::Sortkeys = \&my_filter;
my $foo = { map { (ord, "$_$_$_") } 'I'..'Q' };
my $bar = { %$foo };
my $baz = { reverse %$foo };
print Dumper [ $foo, $bar, $baz ];
sub my_filter {
my ($hash) = @_;
# return an array ref containing the hash keys to dump
# in the order that you want them to be dumped
return [
# Sort the keys of %$foo in reverse numeric order
$hash eq $foo ? (sort {$b <=> $a} keys %$hash) :
# Only dump the odd number keys of %$bar
$hash eq $bar ? (grep {$_ % 2} keys %$hash) :
# Sort keys in default order for all other hashes
(sort keys %$hash)
];
}
๐ BUGS ๐
okay bestie, gather round, because there are a few little gremlins in here and you deserve to know about them before they bite you ๐
- so like,
<yellow>Perl subroutine call semantics</yellow>have limitations, and one of them is that you cannot pass an array or hash directly. nope. not happening. you gotta prepend it with a\and pass its reference instead. the docs literally say "This will be remedied in time, now that Perl has subroutine prototypes." so likeโฆ someday? ๐ in the meantime, bestie, you need to use the extended usage form, and prepend the name with a*to output it as a hash or array. that's the move ๐ฅ Data::Dumperliterally cheats with CODE references. and I mean cheats cheats. if a code reference shows up in the structure being processed (and you haven't set theDeparseflag), it just inserts an anonymous subroutine containing the string"DUMMY"in its place, and prints a warning ifPurityis set. you canevalthe result, but be so for real right now โ that anonymous sub it creates is just a placeholder ๐ even using theDeparseflag will, in some cases, produce results that behave differently after being passed toeval. see the documentation forB::Deparse. not me warning you twice about the same thing ๐ญ- and finally:
SCALARobjects have the weirdest lookingblessworkaround. that's it. that's the whole bullet. it's giving chaos, it's giving cursed, it's giving "why does it look like that" ๐ซ
๐ NOTE
BIG one, bestie, this one matters: different runs of Perl will have different ordering of hash keys. ๐ฑ
and no, that's not a bug, that's intentional. the change was done for greater security โ go read "Algorithmic Complexity Attacks" in perlsec if you want the full lore ๐ง
what this means for you practically: different runs of Perl will have different Data::Dumper outputs if the data contains hashes. so if you're out here diffing two dumps and they don't match, don't panic, it's not you, it's the hash seed ๐ธ
if you need to have identical Data::Dumper outputs from different runs of Perl, use the environment variable PERL_HASH_SEED โ see "PERL_HASH_SEED" in perlrun. using this restores the old (platform-specific) ordering. and honestly? an even prettier solution might be to use the Sortkeys filter of Data::Dumper. lowkey the cleaner glow-up โจ
bestie reminder: hash order is not stable across runs. if you compared two dumps and they were different, that's the feature, not a crisis. ๐
๐ AUTHOR ๐
Gurusamy Sarathy โ and their email is right there: gsar@activestate.com ๐ง
Copyright (c) 1996-2019 Gurusamy Sarathy. All rights reserved. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. ๐ซถ
๐ VERSION ๐
Version 2.191
๐ SEE ALSO ๐
perl(1)โ yes, just the one. go touch base with your roots, babe ๐ฑ
and that's a wrap on the whole page, bestie!! you made it all the way through, I'm so proud of you ๐ฅน๐ go forth and dump responsibly. this was Data::Dumper(3perl), from perl v5.44.0, dated 2026-10-17. slay, you're done, periodt ๐
โจ
๐ฆ where this page comes from
- arch rolling: perl 5.44.0-1 ยท Artistic-1.0-Perl AND GPL-1.0-or-later
- ๐ girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms