📄 dumper.pm
字号:
my($s, $v) = @_; defined($v) ? (($s->{quotekeys} = $v), return $s) : $s->{quotekeys};}sub Bless { my($s, $v) = @_; defined($v) ? (($s->{'bless'} = $v), return $s) : $s->{'bless'};}sub Maxdepth { my($s, $v) = @_; defined($v) ? (($s->{'maxdepth'} = $v), return $s) : $s->{'maxdepth'};}# used by qquote belowmy %esc = ( "\a" => "\\a", "\b" => "\\b", "\t" => "\\t", "\n" => "\\n", "\f" => "\\f", "\r" => "\\r", "\e" => "\\e",);# put a string value in double quotessub qquote { local($_) = shift; s/([\\\"\@\$])/\\$1/g; return qq("$_") unless /[^ !"\#\$%&'()*+,\-.\/0-9:;<=>?\@A-Z[\\\]^_`a-z{|}~]/; # fast exit my $high = shift || ""; s/([\a\b\t\n\f\r\e])/$esc{$1}/g; if (ord('^')==94) { # ascii # no need for 3 digits in escape for these s/([\0-\037])(?!\d)/'\\'.sprintf('%o',ord($1))/eg; s/([\0-\037\177])/'\\'.sprintf('%03o',ord($1))/eg; # all but last branch below not supported --BEHAVIOR SUBJECT TO CHANGE-- if ($high eq "iso8859") { s/([\200-\240])/'\\'.sprintf('%o',ord($1))/eg; } elsif ($high eq "utf8") {# use utf8;# $str =~ s/([^\040-\176])/sprintf "\\x{%04x}", ord($1)/ge; } elsif ($high eq "8bit") { # leave it as it is } else { s/([\200-\377])/'\\'.sprintf('%03o',ord($1))/eg; } } else { # ebcdic s{([^ !"\#\$%&'()*+,\-.\/0-9:;<=>?\@A-Z[\\\]^_`a-z{|}~])(?!\d)} {my $v = ord($1); '\\'.sprintf(($v <= 037 ? '%o' : '%03o'), $v)}eg; s{([^ !"\#\$%&'()*+,\-.\/0-9:;<=>?\@A-Z[\\\]^_`a-z{|}~])} {'\\'.sprintf('%03o',ord($1))}eg; } return qq("$_");}1;__END__=head1 NAMEData::Dumper - stringified perl data structures, suitable for both printing and C<eval>=head1 SYNOPSIS 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::Dump::Purity = 1; eval Data::Dumper->Dump([$foo, $bar], [qw(foo *ary)]); } # OO usage $d = Data::Dumper->new([$foo, $bar], [qw(foo *ary)]); ... print $d->Dump; ... $d->Purity(1)->Terse(1)->Deepcopy(1); eval $d->Dump;=head1 DESCRIPTIONGiven a list of scalars or reference variables, writes out their contents inperl syntax. The references can also be objects. The contents of eachvariable is output in a single Perl statement. Handles self-referentialstructures correctly.The return value can be C<eval>ed to get back an identical copy of theoriginal reference structure.Any references that are the same as one of those passed in will be namedC<$VAR>I<n> (where I<n> is a numeric suffix), and other duplicate referencesto substructures within C<$VAR>I<n> will be appropriately labeled using arrownotation. You can specify names for individual values to be dumped if youuse the C<Dump()> method, or you can change the default C<$VAR> prefix tosomething else. See C<$Data::Dumper::Varname> and C<$Data::Dumper::Terse>below.The default output of self-referential structures can be C<eval>ed, but thenested references to C<$VAR>I<n> will be undefined, since a recursivestructure cannot be constructed using one Perl statement. You should set theC<Purity> flag to 1 to get additional statements that will correctly fill inthese references.In the extended usage form, the references to be dumped can be givenuser-specified names. If a name begins with a C<*>, the output will describe the dereferenced type of the supplied reference for hashes andarrays, and coderefs. Output of names will be avoided where possible ifthe C<Terse> flag is set.In many cases, methods that are used to set the internal state of theobject will return the object itself, so method calls can be convenientlychained together.Several styles of output are possible, all controlled by settingthe C<Indent> flag. See L<Configuration Variables or Methods> below for details.=head2 Methods=over 4=item I<PACKAGE>->new(I<ARRAYREF [>, I<ARRAYREF]>)Returns a newly created C<Data::Dumper> object. The first argument is ananonymous array of values to be dumped. The optional second argument is ananonymous array of names for the values. The names need not have a leadingC<$> sign, and must be comprised of alphanumeric characters. You can begina name with a C<*> to specify that the dereferenced type must be dumpedinstead of the reference itself, for ARRAY and HASH references.The prefix specified by C<$Data::Dumper::Varname> will be used with anumeric suffix if the name for a value is undefined.Data::Dumper will catalog all references encountered while dumping thevalues. Cross-references (in the form of names of substructures in perlsyntax) will be inserted at all possible points, preserving any structuralinterdependencies in the original set of values. Structure traversal isdepth-first, and proceeds in order from the first supplied value tothe last.=item I<$OBJ>->Dump I<or> I<PACKAGE>->Dump(I<ARRAYREF [>, I<ARRAYREF]>)Returns the stringified form of the values stored in the object (preservingthe order in which they were supplied to C<new>), subject to theconfiguration options below. In a list context, it returns a listof strings corresponding to the supplied values.The second form, for convenience, simply calls the C<new> method on itsarguments before dumping the object immediately.=item I<$OBJ>->Seen(I<[HASHREF]>)Queries or adds to the internal table of already encountered references.You must use C<Reset> to explicitly clear the table if needed. Suchreferences are not dumped; instead, their names are inserted wherever theyare encountered subsequently. This is useful especially for properlydumping subroutine references.Expects a anonymous hash of name => value pairs. Same rules apply for namesas in C<new>. If no argument is supplied, will return the "seen" list ofname => value pairs, in a list context. Otherwise, returns the objectitself.=item I<$OBJ>->Values(I<[ARRAYREF]>)Queries or replaces the internal array of values that will be dumped.When called without arguments, returns the values. Otherwise, returns theobject itself.=item I<$OBJ>->Names(I<[ARRAYREF]>)Queries or replaces the internal array of user supplied names for the valuesthat will be dumped. When called without arguments, returns the names.Otherwise, returns the object itself.=item I<$OBJ>->ResetClears the internal table of "seen" references and returns the objectitself.=back=head2 Functions=over 4=item Dumper(I<LIST>)Returns the stringified form of the values in the list, subject to theconfiguration options below. The values will be named C<$VAR>I<n> in theoutput, where I<n> is a numeric suffix. Will return a list of stringsin a list context.=back=head2 Configuration Variables or MethodsSeveral configuration variables can be used to control the kind of outputgenerated when using the procedural interface. These variables are usuallyC<local>ized in a block so that other parts of the code are not affected bythe change. These variables determine the default state of the object created by callingthe C<new> method, but cannot be used to alter the state of the objectthereafter. The equivalent method names should be used instead to queryor 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.=over 4=item $Data::Dumper::Indent I<or> I<$OBJ>->Indent(I<[NEWVAL]>)Controls the style of indentation. It can be set to 0, 1, 2 or 3. Style 0spews output without any newlines, indentation, or spaces between listitems. It is the most compact format possible that can still be calledvalid perl. Style 1 outputs a readable form with newlines but no fancyindentation (each level in the structure is simply indented by a fixedamount of whitespace). Style 2 (the default) outputs a very readable formwhich takes into account the length of hash keys (so the hash value linesup). Style 3 is like style 2, but also annotates the elements of arrayswith their index (but the comment is on its own line, so array outputconsumes twice the number of lines). Style 2 is the default.=item $Data::Dumper::Purity I<or> I<$OBJ>->Purity(I<[NEWVAL]>)Controls the degree to which the output can be C<eval>ed to recreate thesupplied reference structures. Setting it to 1 will output additional perlstatements that will correctly recreate nested references. The default is0.=item $Data::Dumper::Pad I<or> I<$OBJ>->Pad(I<[NEWVAL]>)Specifies the string that will be prefixed to every line of the output.Empty string by default.=item $Data::Dumper::Varname I<or> I<$OBJ>->Varname(I<[NEWVAL]>)Contains the prefix to use for tagging variable names in the output. Thedefault is "VAR".=item $Data::Dumper::Useqq I<or> I<$OBJ>->Useqq(I<[NEWVAL]>)When set, enables the use of double quotes for representing string values.Whitespace other than space will be represented as C<[\n\t\r]>, "unsafe"characters will be backslashed, and unprintable characters will be output asquoted octal integers. Since setting this variable imposes a performancepenalty, the default is 0. C<Dump()> will run slower if this flag is set,since the fast XSUB implementation doesn't support it yet.=item $Data::Dumper::Terse I<or> I<$OBJ>->Terse(I<[NEWVAL]>)When set, Data::Dumper will emit single, non-self-referential values asatoms/terms rather than statements. This means that the C<$VAR>I<n> nameswill be avoided where possible, but be advised that such output may notalways be parseable by C<eval>.=item $Data::Dumper::Freezer I<or> $I<OBJ>->Freezer(I<[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 tostringify it. This method can alter the contents of the object (if, forinstance, it contains data allocated from C), and even rebless it in adifferent package. The client is responsible for making sure the specifiedmethod can be called via the object, and that the object ends up containingonly perl data types after the method has been called. Defaults to an emptystring.=item $Data::Dumper::Toaster I<or> $I<OBJ>->Toaster(I<[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 dumpedusing the syntax C<bless(DATA, CLASS)->METHOD()>. Note that this means thatthe method specified will have to perform any modifications required on theobject (like creating new state within it, and/or reblessing it in adifferent package) and then return it. The client is responsible for makingsure the method can be called via the object, and that it returns a validobject. Defaults to an empty string.=item $Data::Dumper::Deepcopy I<or> $I<OBJ>->Deepcopy(I<[NEWVAL]>)Can be set to a boolean value to enable deep copies of structures.Cross-referencing will then only be done when absolutely essential(i.e., to break reference cycles). Default is 0.=item $Data::Dumper::Quotekeys I<or> $I<OBJ>->Quotekeys(I<[NEWVAL]>)Can be set to a boolean value to control whether hash keys are quoted.A false value will avoid quoting hash keys when it looks like a simplestring. Default is 1, which will always enclose hash keys in quotes.=item $Data::Dumper::Bless I<or> $I<OBJ>->Bless(I<[NEWVAL]>)Can be set to a string that specifies an alternative to the C<bless>builtin operator used to create objects. A function with the specifiedname should exist, and should accept the same arguments as the builtin.Default is C<bless>.=item $Data::Dumper::Maxdepth I<or> $I<OBJ>->Maxdepth(I<[NEWVAL]>)Can be set to a positive integer that specifies the depth beyond whichwhich we don't venture into a structure. Has no effect whenC<Data::Dumper::Purity> is set. (Useful in debugger when we often don'twant to see more than enough). Default is 0, which means there is no maximum depth. =back=head2 Exports=over 4=item Dumper=back=head1 EXAMPLESRun these code snippets to get a quick feel for the behavior of thismodule. When you are through with these examples, you may want toadd or change the various configuration variables described above,to see their behavior. (See the testsuite in the Data::Dumperdistribution 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); ######## # 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 Foo; 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;=head1 BUGSDue to limitations of Perl subroutine call semantics, you cannot pass anarray or hash. Prepend it with a C<\> to pass its reference instead. Thiswill be remedied in time, with the arrival of prototypes in later versionsof Perl. For now, you need to use the extended usage form, and prepend thename with a C<*> to output it as a hash or array.C<Data::Dumper> cheats with CODE references. If a code reference isencountered in the structure being processed, an anonymous subroutine thatcontains the string '"DUMMY"' will be inserted in its place, and a warningwill be printed if C<Purity> is set. You can C<eval> the result, but bearin mind that the anonymous sub that gets created is just a placeholder.Someday, perl will have a switch to cache-on-demand the stringrepresentation of a compiled piece of code, I hope. If you have priorknowledge of all the code refs that your data structures are likelyto have, you can use the C<Seen> method to pre-seed the internal referencetable and make the dumped output point to them, instead. See L<EXAMPLES>above.The C<Useqq> flag makes Dump() run slower, since the XSUB implementationdoes not support it.SCALAR objects have the weirdest looking C<bless> workaround.=head1 AUTHORGurusamy Sarathy gsar@activestate.comCopyright (c) 1996-98 Gurusamy Sarathy. All rights reserved.This program is free software; you can redistribute it and/ormodify it under the same terms as Perl itself.=head1 VERSIONVersion 2.11 (unreleased)=head1 SEE ALSOperl(1)=cut
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -