File Coverage

blib/lib/Data/Dump/Streamer.pm
Criterion Covered Total %
statement 1184 1411 83.9
branch 623 898 69.3
condition 302 474 63.7
subroutine 90 103 87.3
pod 22 32 68.7
total 2221 2918 76.1


line stmt bran cond sub pod time code
1             package Data::Dump::Streamer;
2 24     24   1330179 use strict;
  24         257  
  24         791  
3 24     24   130 use warnings;
  24         49  
  24         711  
4 24     24   136 use warnings::register;
  24         46  
  24         4244  
5              
6 24     24   186 use B ();
  24         56  
  24         584  
7 24     24   143 use B::Deparse ();
  24         48  
  24         485  
8 24     24   14939 use B::Utils ();
  24         142903  
  24         638  
9 24     24   14919 use Data::Dumper ();
  24         166957  
  24         714  
10 24     24   173 use DynaLoader ();
  24         54  
  24         335  
11 24     24   113 use Exporter ();
  24         54  
  24         313  
12 24     24   12007 use IO::File ();
  24         217861  
  24         695  
13 24     24   217 use Symbol ();
  24         50  
  24         388  
14 24     24   18606 use Text::Abbrev ();
  24         1277  
  24         631  
15 24     24   17103 use Text::Balanced ();
  24         318780  
  24         865  
16 24     24   186 use overload ();
  24         53  
  24         438  
17              
18 24     24   20266 use Data::Dump::Streamer::_::Printers;
  24         67  
  24         1142  
19              
20             # use overload qw("" printit); # does diabolical stuff.
21              
22 24         2785 use vars qw(
23             $VERSION
24             $XS_VERSION
25             $AUTOLOAD
26             @ISA
27             @EXPORT @EXPORT_OK @EXPORT_FAIL %EXPORT_TAGS
28             %Freeze
29             %Thaw
30             $DEBUG
31             $HasPadWalker
32 24     24   154 );
  24         49  
33              
34             $DEBUG=0;
35 24     24   1879 BEGIN{ $HasPadWalker=eval "use PadWalker 0.99; 1"; }
  24     24   11016  
  24         16438  
  24         832  
36              
37             BEGIN {
38 24     24   171 $VERSION ='2.41';
39 24         47 $XS_VERSION = $VERSION;
40 24         1537 $VERSION = eval $VERSION; # used for beta stuff.
41 24         502 @ISA = qw(Exporter DynaLoader);
42 24         109 @EXPORT=qw(Dump DumpLex DumpVars);
43 24         162 @EXPORT_OK = qw(
44             Dump
45             DumpLex
46             DumpVars
47             Stream
48             alias_av
49             alias_hv
50             alias_ref
51             push_alias
52             dualvar
53              
54             alias_to
55              
56             blessed
57             reftype
58             refaddr
59             refcount
60             sv_refcount
61             looks_like_number
62             regex
63             readonly
64             make_ro
65             _make_ro
66             reftype_or_glob
67             refaddr_or_glob
68             globname
69             is_numeric
70              
71             all_keys
72             legal_keys
73             hidden_keys
74             lock_ref_keys
75             lock_keys
76             lock_ref_keys_plus
77             lock_keys_plus
78             SvREADONLY_ref
79             SvREFCNT_ref
80             isweak
81             weaken
82             weak_refcount
83              
84             readonly_set
85              
86             Dumper
87             DDumper
88              
89             alias
90             sqz
91             usqz
92             );
93              
94 24         532 %EXPORT_TAGS = (
95             undump => [ qw( alias_av alias_hv alias_ref make_ro
96             lock_ref_keys
97             lock_keys
98             lock_ref_keys_plus
99             lock_keys_plus
100             alias_to
101             dualvar
102             weaken
103             usqz
104             )
105             ],
106             special=> [ qw( readonly_set ) ],
107             all => [ @EXPORT,@EXPORT_OK ],
108             alias => [ qw( alias_av alias_hv alias_ref push_alias ) ],
109             bin => [ @EXPORT_OK ],
110             Dumper => [ qw( Dumper DDumper )],
111             util => [ qw (
112             dualvar
113             blessed reftype refaddr refcount sv_refcount
114             readonly looks_like_number regex is_numeric
115             make_ro readonly_set reftype_or_glob
116             refaddr_or_glob globname
117             weak_refcount isweak weaken
118             )
119             ],
120              
121             );
122              
123              
124 0     0 0 0 sub alias_to { return shift }
125              
126             #warn $VERSION;
127 24         10125 Data::Dump::Streamer->bootstrap($XS_VERSION);
128 24 50       273 if ($]>=5.013010) {
    0          
    0          
129             # As I write this, 5.13.10 doesn't exist so I'm guessing that
130             # we can begin using the ordinary core function again.
131 24 50   24   2283 eval q[
  24         192  
  24         54  
  24         6550  
132             use re qw(regexp_pattern is_regexp);
133             *regex= *regexp_pattern;
134             ] or die $@;
135             }
136             elsif ($]>=5.013006) {
137             # Perl-5.13.6 through perl-5.13.9 began returning modifier
138             # flags that weren't yet legal at the time.
139 0 0       0 eval q[
140             use re qw(regexp_pattern is_regexp);
141             sub regex {
142             if (wantarray) {
143             my ($pat,$mod) = regexp_pattern($_[0]);
144             if ($mod) {
145             $mod =~ tr/dlua?//d;
146             }
147             return ($pat,$mod);
148             }
149             else {
150             return scalar regexp_pattern($_[0]);
151             }
152             }
153             1;
154             ] or die $@;
155             }
156             elsif ($]>=5.009004) {
157 0 0       0 eval q[
158             use re qw(regexp_pattern is_regexp);
159             *regex= *regexp_pattern;
160             1;
161             ] or die $@;
162             }
163             else {
164 0         0 eval q[sub is_regexp($) { defined regex($_[0]) }];
165             }
166 24 50       191 if ($]<=5.008) {
167 0         0 *hidden_keys=sub(\%) { return () };
  0         0  
168 0         0 *legal_keys=sub(\%) { return keys %{$_[0]} };
  0         0  
  0         0  
169 0         0 *all_keys=sub(\%\@\@) { @{$_[1]}=keys %{$_[0]}; @$_[2]=(); };
  0         0  
  0         0  
  0         0  
  0         0  
170             }
171 24 50       97 if ( $]<5.008 ) {
172 24     24   199 no strict 'refs';
  24         65  
  24         10073  
173 0         0 foreach my $sub (qw(lock_keys lock_keys_plus )) {
174             *$sub=sub(\%;@) {
175 0         0 warnings::warn "$sub doesn't do anything before Perl 5.8.0\n";
176 0         0 return $_[0];
177             }
178 0         0 }
179 0         0 foreach my $sub (qw(lock_ref_keys lock_ref_keys_plus )) {
180             *$sub=sub($;@) {
181 0         0 warnings::warn "$sub doesn't do anything before Perl 5.8.0\n";
182 0         0 return $_[0];
183             }
184 0         0 }
185             } else {
186             eval <<'EO_HU'
187             use Hash::Util qw(lock_keys);
188             sub lock_ref_keys($;@) {
189             my $hash=shift;
190             Carp::confess("lock_ref_keys(): Not a ref '$hash'")
191             unless ref $hash;
192             lock_keys(%$hash,@_);
193             $hash
194             }
195             EO_HU
196 24 50   24 0 1967 ;
  24     6   14350  
  24         73799  
  24         160  
  6         15132  
  6         25  
  6         28  
  6         297  
197             *lock_ref_keys_plus=sub($;@){
198 43     43   7798 my ($hash,@keys)=@_;
199 43         68 my @delete;
200 43         112 Internals::hv_clear_placeholders(%$hash);
201 43         110 foreach my $key (@keys) {
202 86 100       185 unless (exists($hash->{$key})) {
203 85         151 $hash->{$key}=undef;
204 85         152 push @delete,$key;
205             }
206             }
207 43         101 SvREADONLY_ref($hash,1);
208 43         63 delete @{$hash}{@delete};
  43         97  
209 43         257 $hash
210 24         3605 };
211 24     6   113 *lock_keys_plus=sub(\%;@){lock_ref_keys_plus(@_)};
  6         4688  
212             }
213 24 50       128 if ($] <= 5.008008) {
214 0         0 *disable_overloading = \&SvAMAGIC_off;
215             *restore_overloading = sub ($$) {
216 0         0 SvAMAGIC_on($_[0], undef);
217              
218             # Visit all classes we are ISA and fetch the () entry from
219             # every stash.
220 0         0 my %done;
221 0         0 my %todo = (
222             $_[0] => undef,
223             UNIVERSAL => undef,
224             );
225 24     24   540 no strict 'refs';
  24         285  
  24         5980  
226 0         0 for my $todo_class (keys %todo) {
227 0         0 delete $todo{$todo_class};
228 0         0 $done{$todo_class} = undef;
229 0         0 for my $isa (@{"${todo_class}::ISA"}) {
  0         0  
230 0 0       0 $todo{$isa} = undef unless exists $done{$isa};
231             }
232             }
233 0         0 };
234             } else {
235             *disable_overloading = sub ($) {
236             # we use eval because $_[0] might be read-only
237             # its a crappy solution, but whatever, it works
238 55     55   91 eval { bless $_[0], 'Does::Not::Exist' };
  55         155  
239 24         93 };
240             *restore_overloading = sub ($$) {
241 55     55   86 eval { bless $_[0], $_[1] }
  55         167  
242 24         82 };
243             }
244 24         79 my %fail=map { ( $_ => 1 ) } @EXPORT_FAIL;
  0         0  
245 24         66 @EXPORT_OK=grep { !$fail{$_} } @EXPORT_OK;
  1008         3667  
246             }
247              
248             sub import {
249 26     26   1104 my ($pkg) = @_;
250 26         78 my ($idx, $alias);
251              
252 26 100       234 if ($idx = (grep lc($_[$_]) eq 'as', 0..$#_)) {
253             #print "found alias at $idx:\n";
254 2         8 ($idx, $alias) = splice(@_, $idx, 2);
255             #print "found alias: $idx => $alias\n";
256              
257 24     24   185 no strict 'refs';
  24         75  
  24         22454  
258 2         3 *{$alias.'::'} = *{__PACKAGE__.'::'};
  2         50  
  2         8  
259             }
260 26         7554 $pkg->export_to_level(1,@_);
261             }
262              
263             # NOTE
264             # ----
265             # This module uses the term 'sv' in a way that is misleading.
266             # It doesn't always mean the same as it would in the core.
267             #
268             # 1. data is breadth first traversed first, in the pretty much
269             # self contained Data() routine which farms out a bit to
270             # _reg_ref and _reg_scalar which handle "registering" items for
271             # later use, such as their depth, refcount, "name", etc. But
272             # ONLY for references and scalars whose refcount is over 2.
273             # Most real SV's will have a refcount of 2 when we look at them
274             # (from the perl side) so we actually don't know about them (trust me)
275             # They _cant_ be referenced twice, and they can't be aliased so we can
276             # can just ignore them until the second pass.
277             # 2.Once this has happened Out() is called which starts off a
278             # normal depth first traverse over the structure. It calls into
279             # 3._dump_sv which in the case of a reference falls through to _dump_rv.
280             # Aliasing and a bunch of stuff like that are checked here before we even
281             # look at the reference type.
282             # 4.If its a ref we fall through to dumping the reference in _dump_rv.
283             # Here we handle duplicate refs, and manage depth checks, blessing, refs
284             #(which is scary nasty horrible code) and then pass on to _dump_type where
285             # type is one of 'code', 'qr', 'array' etc. Each of these which have children
286             # then call back into _dump_sv as required.
287             # 5. Because of the way perl works, we can't emit anything more than a DAG in a
288             # single statement, so for more complex structures we need to add in the broken
289             # links. I call these "fix statements", and they encompass copying reference
290             # values, creating aliases, or even dumping globs. When a fix statement is needed
291             # any of the _dump_foo methods will call _add_fix and add to the list of fixes.
292             # after every root level _dump_sv call from Out() any fix statements possible to be
293             # resolved will be emitted and removed from the fix list. This happens in
294             # _dump_apply_fix, which is another piece of horrible code.
295             #
296             # Anyway, its terribly ugly, but for anything I can think to throw at i works.
297             # demerphq
298              
299             =encoding utf8
300              
301             =head1 NAME
302              
303             Data::Dump::Streamer - Accurately serialize a data structure as Perl code.
304              
305             =head1 SYNOPSIS
306              
307             use Data::Dump::Streamer;
308             use DDS; # optionally installed alias
309              
310             Dump($x,$y); # Prints to STDOUT
311             Dump($x,$y)->Out(); # " "
312              
313             my $o=Data::Dump::Streamer->new(); # Returns a new ...
314             my $o=Dump(); # ... uninitialized object.
315              
316             my $o=Dump($x,$y); # Returns an initialized object
317             my $s=Dump($x,$y)->Out(); # " a string of the dumped obj
318             my @l=Dump($x,$y); # " a list of code fragments
319             my @l=Dump($x,$y)->Out(); # " a list of code fragments
320              
321             Dump($x,$y)->To(\*STDERR)->Out(); # Prints to STDERR
322              
323             Dump($x,$y)->Names('foo','bar') # Specify Names
324             ->Out();
325              
326             Dump($x,$y)->Indent(0)->Out(); # No indent
327              
328             Dump($x,$y)->To(\*STDERR) # Output to STDERR
329             ->Indent(0) # ... no indent
330             ->Names('foo','bar') # ... specify Names
331             ->Out(); # Print...
332              
333             $o->Data($x,$y); # OO form of what Dump($x,$y) does.
334             $o->Names('Foo','Names'); # ...
335             $o->Out(); # ...
336              
337             =head1 DESCRIPTION
338              
339             Given a list of scalars or reference variables, writes out
340             their contents in perl syntax. The references can also be
341             objects. The contents of each variable is output using the least
342             number of Perl statements as convenient, usually only one.
343             Self-referential structures, closures, and objects are output
344             correctly.
345              
346             The return value can be evaled to get back an identical copy
347             of the original reference structure. In some cases this may
348             require the use of utility subs that
349             L will optionally
350             export.
351              
352             This module is very similar in concept to the core module
353             L, with the major differences
354             being that this module is designed to output to a stream
355             instead of constructing its output in memory (trading speed
356             for memory), and that the traversal over the data structure
357             is effectively breadth first versus the depth first
358             traversal done by the others.
359              
360             In fact the data structure is scanned twice, first in
361             breadth first mode to perform structural analysis, and then
362             in depth first mode to actually produce the output, but
363             obeying the depth relationships of the first pass.
364              
365             =head2 Caveats Dumping Closures (CODE Refs)
366              
367             As of version 1.11 DDS has had the ability to dump closures properly. This
368             means that the lexicals that are bound to the closure are dumped along
369             with the subroutine that uses them. This makes it much easier to debug
370             code that uses closures and to a certain extent provides a persistency
371             framework for closure based code. The way this works is that DDS figures
372             out what all the lexicals are that are bound to CODE refs it is dumping
373             and then pretends that it had originally been called with all of them as
374             its arguments, (along with the original arguments as well of course.)
375              
376             One consequence of the way the dumping process works is that all of the
377             recreated subroutines will be in the same scope. This of course can lead
378             to collisions as two subroutines can easily be bound to different
379             variables that have the same name.
380              
381             The way that DDS resolves these collisions is that it renames one of the
382             variables with a special name so that presumably there are no collisions.
383             However this process is very simplistic with no checks to prevent
384             collisions with other lexicals or other globals that may be used by other
385             dumped code. In some situations it may be necessary to change the default
386             value of the rename template which may be done by using the C
387             method.
388              
389             Similarly to the problem of colliding lexicals is the problem of colliding
390             lexicals and globals. DDS pays no attention to globals when dumping
391             closures which can potentially result in lexicals being declared that will
392             eclipse their global namesake. There is currently no way around this other
393             than to avoid accessing a global and a lexical with the same name from the
394             subs being dumped. An example is
395              
396             my $a = sub { $a++ };
397             Dump( sub { $a->() } );
398              
399             which will not be dumped correctly. Generally speaking this kind of thing
400             is bad practice anyway, so this should probably be viewed as a "feature".
401             :-)
402              
403             Generally if the closures being dumped avoid accessing lexicals and
404             globals with the same name from out of scope and that all of the CODE
405             being dumped avoids vars with the C in their names the dumps
406             should be valid and should eval back into existence properly.
407              
408             Note that the behaviour of dumping closures is subject to change in future
409             versions as its possible that I will put some additional effort into more
410             sophisticated ways of avoiding name collisions in the dump.
411              
412             =head1 USAGE
413              
414             While Data::Dump::Streamer is at heart an object oriented module, it is
415             expected (based on experience with using L)
416             that the common case will not exploit these features. Nevertheless the
417             method based approach is convenient and accordingly a compromise hybrid
418             approach has been provided via the C subroutine. Such as
419              
420             Dump($foo);
421             $as_string= Dump($foo)->Out();
422              
423             All attribute methods are designed to be chained together. This means
424             that when used as set attribute (called with arguments) they return the
425             object they were called against. When used as get attributes (called
426             without arguments) they return the value of the attribute.
427              
428             From an OO point of view the key methods are the C and C
429             methods. These correspond to the breadth first and depth first traversal,
430             and need to be called in this order. Some attributes I be set prior
431             to the C phase and some need only be set before the C
432             phase.
433              
434             Attributes once set last the lifetime of the object, unless explicitly
435             reset.
436              
437             =head2 Controlling Object Representation
438              
439             This module provides hooks to allow objects to override how they are
440             represented. The basic idea is that a subroutine (or method) is provided
441             which is responsible for the override. The return of the method governs
442             how the object will be represented when dumped, and how it will be
443             restored. The basic calling convention is
444              
445             my ( $proxy, $thaw, $postop )= $callback->($obj);
446             #or = $obj->$method();
447              
448             The L|/Freezer> method controls what methods to use as a default method
449             and also allows per class overrides. When dumping an object of a given
450             class the first time it tries to execute the class specific handler if
451             it is specified, then the user specific generic handler if its been
452             specified and then "DDS_freeze". This means that class authors can
453             implement a C method and their objects will automatically
454             be serialized as necessary. B that if either the class specific or
455             generic handler is defined but false C will not be used
456             even if it is present.
457              
458             The interface of the L|/Freezer> handler in detail is as follows:
459              
460             =over 4
461              
462             =item B>
463              
464             The object being dumped.
465              
466             =item B>
467              
468             This is what will be dumped instead of C<$obj>. It may be one of
469             the following values:
470              
471             =over 8
472              
473             =item I> (first time only)
474              
475             On the first time a serialization hook is called in a dump it may return
476             undef or the empty list to indicate that it shouldn't be used again for
477             this class during this pass. Any other time undef is treated the same
478             as false.
479              
480             =item I
481              
482             A false value for C<$proxy> is taken to mean that it should be ignored.
483             Its like saying IgnoreClass(ref($obj)); B that undef has a special
484             meaning when the callback is called the first time.
485              
486             =item I
487              
488             A reference that will be dumped instead of the object.
489              
490             =item I
491              
492             A string that is to be treated as code and inserted directly into the
493             dump stream as a proxy for the original. Note that the code must be
494             able to execute inline or in other words must evaluate to a perl EXPR.
495             Use C to wrap multistatement code.
496              
497             =back
498              
499             =item B>
500              
501             This values is used to allow extra control over how the object will be
502             recreated when dumped. It is used for converting the C<$proxy> representation
503             into the real thing. It is only relevant when C<$proxy> is a reference.
504              
505             =over 8
506              
507             =item I
508              
509             Indicates no thaw action is to be included for this object.
510              
511             =item I
512              
513             A string matching C<< /^(->)?((?:\w*::)\w+)(\(\))?$/ >> in which case it
514             is taken as a sub name when the string ends in () and a method name
515             when the string doesn't. If the C<< -> >> is present then the sub or method
516             is called inline. If it is not then the sub or method is called
517             after the main dump.
518              
519             =item I
520              
521             Any other string, in which case the result will be taken as code
522             which will be emitted after the main dump. It will be wrapped
523             in a for loop that aliases C<$_> to the variable in question.
524              
525             =back
526              
527             =item B>
528              
529             This is the similar to C<$thaw> but is called in process instead
530             of being emitted as part of the dump. Any return is ignored.
531             It is only relevant when C<$proxy> is a reference.
532              
533             =over 8
534              
535             =item I
536              
537             No postdump action is to occur.
538              
539             =item I
540              
541             The code ref will be called after serialization is complete
542             with the object as the argument.
543              
544             =item I
545              
546             The method will be called after serialization is complete
547              
548             =back
549              
550             =back
551              
552             An example DDS_freeze method is one I had to put together for an object
553             which contained a key whose value was a ref to an array tied to the value
554             of another key. Dumping this got crazy, so I wanted to suppress dumping
555             the tied array. I did it this way:
556              
557             sub DDS_freeze {
558             my $self=shift;
559             delete $self->{'tie'};
560             return ($self,'->fix_tie','fix_tie');
561             }
562              
563             sub fix_tie {
564             my $self=shift;
565             if ( ! $self->{'tie'} ) {
566             $self->{str}="" unless defined $self->{str};
567             tie my @a, 'Tie::Array::PackedC', $self->{str};
568             $self->{'tie'} = \@a;
569             }
570             return $self;
571             }
572              
573             The C<$postop> means the object is relatively unaffected after the
574             dump, the C<$thaw> says that we should also include the method
575             inline as we dump. An example dump of an object like this might be
576              
577             $Foo1=bless({ str=>'' },'Foo')->fix_tie();
578              
579             Wheras if we omit the C<< -> >> then we would get:
580              
581             $Foo1=bless({ str=>'' },'Foo');
582             $Foo1->fix_tie();
583              
584             In our example it wouldn't actually make a difference, but the former
585             style can be nicer to read if the object is embedded in another.
586             However the non arrow notation is slightly more dangerous, in that
587             its possible that the internals of the object will not be fully linked
588             when the method is evaluated. The second form guarantees that the object
589             will be fully linked when the method is evaluated.
590              
591             See L for a different way
592             to control the representation of hash based objects.
593              
594             =head2 Controlling Hash Traversal and Display Order
595              
596             When dumping a hash you may control the order the keys will be output
597             and which keys will be included. The basic idea is to specify a subroutine
598             which takes a hash as an argument and returns a reference to an array
599             containing the keys to be dumped.
600              
601             You can use the L routine or the L routine to
602             specify the sorter to be used.
603              
604             The routine will be called in the following way:
605              
606             ( $key_array, $thaw ) = $sorter->($hash,($pass=0),$addr,$class);
607             ( $key_array,) = $sorter->($hash,($pass=1),$addr,$class);
608              
609             C<$hash> is the hash to be dumped, C<$addr> is the refaddr() of the
610             C<$hash>, and C<$class> will be set if the hash has been blessed.
611              
612             When C<$pass> is 0 the C<$thaw> variable may be supplied as well as the
613             keyorder. If it is defined then it specifies what thaw action to perform
614             after dumping the hash. See L|/$thaw> in L
615             Representation> for details as to how it works. This allows an object
616             to define those keys needed to recreate itself properly, and a followup
617             hook to recreate the rest.
618              
619             B that if a L method is defined and returns
620             a L|/$thaw> then the L|/$thaw> returned by the sorter
621             will override it.
622              
623             =head2 Controlling Array Presentation and Run Length Encoding
624              
625             By default Data::Dump::Streamer will "run length encode" array values.
626             This means that when an array value is simple (ie, its not referenced and
627             does contain a reference) and is repeated multiple times the output will
628             be single a list multiplier statement, and not each item output
629             separately. Thus: L|/Dump> will be output something like
630              
631             $ARRAY1 = [ (0) x 4 ];
632              
633             This is particularly useful when dealing with large arrays that are only
634             partly filled, and when accidentally the array has been made very large,
635             such as with the improper use of pseudo-hash notation.
636              
637             To disable this feature you may set the L property to FALSE, by
638             default it is enabled and set to TRUE.
639              
640             =head2 Installing I as a package alias
641              
642             Its possible to have an alias to Data::Dump::Streamer created and
643             installed for easier usage in one liners and short scripts.
644             Data::Dump::Streamer is a bit long to type sometimes. However because this
645             technically means polluting the root level namespace, and having it listed
646             on CPAN, I have elected to have the installer not install it by default.
647             If you wish it to be installed you must explicitly state so when
648             Build.Pl is run:
649              
650             perl Build.Pl DDS [Other Module::Build options]
651              
652             Then a normal './Build test, ./Build install' invocation will install DDS.
653              
654             Using DDS is identical to Data::Dump::Streamer.
655              
656             =head2 use-time package aliasing
657              
658             You can also specify an alias at use-time, then use that alias in the rest
659             of your program, thus avoiding the permanent (but modest) namespace
660             pollution of the previous method.
661              
662             use Data::Dumper::Streamer as => 'DDS';
663              
664             # or if you prefer
665             use Data::Dumper::Streamer;
666             import Data::Dumper::Streamer as => 'DDS';
667              
668             You can use any alias you like, but that doesn't mean you should.. Folks
669             doing as => 'DBI' will be mercilessly ridiculed.
670              
671             =head2 PadWalker support
672              
673             If PadWalker 1.0 is installed you can use DumpLex() to try to
674             automatically determine the names of the vars being dumped. As
675             long as the vars being dumped have my or our declarations in scope
676             the vars will be correctly named. Padwalker will also be used
677             instead of the B:: modules when dumping closures when it is available.
678              
679             =head1 INTERFACE
680              
681             =head2 Data::Dumper Compatibility
682              
683             For drop in compatibility with the Dumper() usage of Data::Dumper, you may
684             request that the L method is exported. It will not be exported by
685             default. In addition the standard Data::Dumper::Dumper() may be exported
686             on request as C. If you provide the tag C<:Dumper> then both will
687             be exported.
688              
689             =over 4
690              
691             =item Dumper
692              
693             =item Dumper LIST
694              
695             A synonym for scalar Dump(LIST)->Out for usage compatibility with
696             L
697              
698             =item DDumper
699              
700             =item DDumper LIST
701              
702             A secondary export of the actual L
703             subroutine.
704              
705             =back
706              
707             =head2 Constructors
708              
709             =over 4
710              
711             =item new
712              
713             Creates a new Data::Dump::Streamer object. Currently takes no
714             arguments and simply returns the new object with a default style
715             configuration.
716              
717             See C for a better way to do things.
718              
719             =cut
720              
721             sub _compressor {
722 4 100   4   11 return "use Data::Dump::Streamer qw(usqz);\n"
723             if !@_;
724 2         7 return sqz($_[0], "usqz('", "')" );
725             }
726              
727             sub new {
728 50     50 1 161248 my $class = shift;
729 50         1191 my $self = bless {
730             style => {
731             hashsep => '=>', # use this to separate key vals
732             arysep => ',',
733             pairsep => ',',
734             optspace => ' ',
735             bless => 'bless()', # use this to bless objects, needs fixing
736              
737             compress => 0, # if nonzero use compressor to compress strings
738             # longer than this value.
739             compressor => \&_compressor,
740              
741             indent => 2, # should we indent at all?
742             indentkeys => 1, # indent keys
743             declare => 0, # predeclare vars? allows refs to root vars if 0
744             sortkeys => {},
745             verbose => 1, # use long names and detailed fill ins
746             dumpglob => 1, # dump glob contents
747             deparseglob => 1,
748             deparse => 1, # deparse code refs?
749             freezer => 'DDS_freeze', # default freezer
750             freeze_class => {}, # freeze classes
751              
752             rle => 1, # run length encode arrays
753             ignore => {}, # ignore classes
754             indentcols => 2, # indent this number of cols
755             ro => 1, # track readonly vars
756             dualvars => 1, # dump dualvars
757             eclipsename => "%s_eclipse_%d",
758              
759             purity => 1, # test
760              
761             terse => 0,
762              
763             # use this if deparse is 0
764             codestub => 'sub { Carp::confess "Dumped code stub!" }',
765             formatstub => 'do{ local *F; eval "format F =\nFormat Stub\n.\n"; *F{FORMAT} }',
766             # use these opts if deparse is 1
767             deparseopts => ["-sCi2v'Useless const omitted'"],
768             special => 0,
769              
770             # not yet implemented
771             array_warn => 10_000, # warn if an array has more than this number of elements
772             array_chop => 32_767, # chop arrays over this size
773             array_max => 1_000_000, # die if arrays have more than this size
774             smart_array => 1, # special handling of very large arrays
775             # with hashes as their 0 index. (pseudo-hash error detection)
776             },
777             debug => 0,
778             cataloged => 0,
779             ref_id => 0,
780             sv_id => 0
781             }, $class;
782              
783 50         311 return $self;
784             }
785              
786             sub _safe_self {
787 1002     1002   1863 my $self = shift;
788 1002 100       2699 unless ( ref $self ) {
789 7         18 $self = $self->new();
790             }
791 1002         6121 return $self;
792             }
793              
794             sub Dumper {
795 0     0 1 0 return scalar Dump(@_)->Out();
796             }
797              
798             sub DDumper {
799 0     0 1 0 return Data::Dumper::Dumper(@_);
800             }
801              
802             #sub _is_utf8 { length $_[0] != do { use bytes; length $_[0] } }
803              
804 0         0 BEGIN {
805 24     24   12673 my $numeric_rex=qr/\A-?(?:0|[1-9]\d*)(\.\d+(?
806              
807             # used by _qquote below
808 24         30779 my %esc = (
809             "\a" => "\\a",
810             "\b" => "\\b",
811             "\t" => "\\t",
812             "\n" => "\\n",
813             "\f" => "\\f",
814             "\r" => "\\r",
815             "\e" => "\\e",
816             );
817              
818             # Taken from Data::Dumper::qquote() 2.12.
819             # Changed utf8 handling from that version
820             # put a string value in double quotes
821             # Fixes by [ysth]
822             sub _qquote {
823 540     540   848 my $str = shift;
824 540         749 my @ret;
825 540         1099 while (length($str)) {
826 540         1467 local($_)=substr($str,0,72,"");
827 540         993 s/([\\\"\@\$])/\\$1/g;
828              
829 540 100       1144 unless (/[^ !""\#\$%&''()*+,\-.\/0-9:;<=>?\@A-Z[\\\]^_`a-z{|}~]/) {
830 508         1169 push @ret,qq("$_"); # fast exit
831 508         1162 next;
832             }
833              
834              
835 32         155 s/([\a\b\t\n\f\r\e])/$esc{$1}/g;
836              
837 32         58 if ( ord('^') == 94 ) {
838             # ascii / utf8
839             # no need for 3 digits in escape if followed by a digit
840 32         146 s/([\0-\037])(?!\d) / sprintf '\\%o', ord($1)/xeg;
  0         0  
841 32         57 s/([\0-\037\177]) / sprintf '\\%03o', ord($1)/xeg;
  0         0  
842              
843 24 100   24   236 if (length $_ != do { use bytes; length $_ }) {
  24         59  
  24         222  
  32         57  
  32         166  
844 24     24   16785 use utf8; #perl 5.6.1 needs this, 5.9.2 doesn't. sigh
  24         408  
  24         221  
845 6         29 s/([\200-\377]) / sprintf '\\%03o', ord($1)/xeg;
  0         0  
846 6         29 s/([^\040-\176])/ sprintf '\\x{%x}', ord($1)/xeg;
  10         60  
847             } else {
848             # must not be under "use utf8" for 5.6.x
849 26         49 s/([\200-\377]) / sprintf '\\%03o', ord($1)/xeg;
  2         13  
850             }
851             } else {
852             # ebcdic
853             s{([^ !""\#\$%&''()*+,\-.\/0-9:;<=>?\@A-Z[\\\]^_`a-z{|}~])(?!\d)}
854             {
855             my $v = ord($1); '\\'.sprintf(($v <= 037 ? '%o' : '%03o'), $v)
856             }eg;
857             s{([^ !""\#\$%&''()*+,\-.\/0-9:;<=>?\@A-Z[\\\]^_`a-z{|}~])}
858             {'\\'.sprintf('%03o',ord($1))}eg;
859 32         136 }
860              
861 540         1525 push @ret,qq("$_");
862             }
863             return join ".\n\t",@ret;
864             }
865              
866              
867 1747     1747   4050 # single quote
868 1747 100       11146 sub _quote {
    100          
869 608         1681 my $v = join "", @_;
870             if ($v=~$numeric_rex) {
871 1131         2284 return $v;
872 1131         4018 } elsif ($v!~/[^\x20-\x7E]/) {
873             $v =~ s/([\\''])/\\$1/g;
874 8         30 return "'$v'";
875             }
876             return _qquote($v);
877             }
878              
879 4764     4764   7439 # quote a key
880 4764 50 33     39155 sub _quotekey {
    100 100        
881 0         0 my $key = shift;
882             if (!defined($key) or $key eq '') {
883 4232         11675 return '""'
884             } elsif ($key=~$numeric_rex or $key =~ /\A-?[A-Za-z_]\w*\z/) {
885 532         1103 return $key
886             } else {
887             _qquote($key);
888             }
889             }
890             }
891              
892             my %ttrans = (
893             reftype( {} ) => '%',
894             reftype( [] ) => '@',
895             reftype( \ 'foo' ) => '$',
896             reftype( \\'foo' ) => '$', # REF
897             reftype( sub{} ) => '&',
898             '' => '$',
899             );
900              
901 790     790   1689  
902             sub _make_name {
903             my ( $self, $obj, $indx ) = @_;
904 790   100     3507 #warn Dumper($self->{unames})."'$self->{unames}'
      100        
905             # : @{$self->{unames}||[]} @{[defined $indx ? $indx : '-']}";
906 790 100       2082 my $uname = ( $self->{unames} || [] )->[ $indx || 0 ];
    100          
907 503   66     2663  
908             unless ($uname) {
909             my $name = blessed($_[1])
910 503 100       1207 || reftype($_[1])
911 2         3 || ((readonly($_[1]) && (\$_[1] != \undef)) ? "RO" : "VAR");
912 2         8 unless ($self->{style}{verbose}) {
913 2   33     14 my $n=1;
914 2   33     15 (my $abr=$name)=~s/(\w)\w*::/$1/g;
      33        
915             $self->{type_abrv}{$name}||=$name;
916             while ($n<=length($abr) and
917 0         0 $self->{type_abrv}{substr($abr,0,$n)} and
918             $self->{type_abrv}{substr($abr,0,$n)} ne $name) {
919 2 50       7 $n++;
920 2         6 }
921             if ($n<=length($abr)) {
922             $self->{type_abrv}{substr($abr,0,$n)}=$name;
923 2         11 return '$' .
924             substr($abr,0,$n) .
925             ( ++$self->{type_ids}{$name} );
926 501         1038 }
927 501         2064 }
928 501         2338 $name =~ s/::/_/g;
929 0         0 ($name)=$name=~/(\w+)/; #take the first word;
930 155   100     540 return '$' . $name . ( ++$self->{type_ids}{$name} );
931 155         771 } elsif ( $uname =~ /^[-*]/ ) {
932 155         476 my $type = reftype( $_[1] ) || '';
933             $uname =~ s//$ttrans{$type}/;
934 132         386 $uname;
935             } else {
936             return '$' . $uname;
937             }
938             }
939              
940             #=item diag
941             #
942             #Outputs to STDOUT a list of all values that have been identified of being
943             #worth of study. For development/debugging purposes only at this point.
944             #
945             #=cut
946 0     0 0 0  
947 0   0     0 sub diag {
948 0         0 my $self=shift;
949             my $handle=shift || \*STDOUT;
950 0         0 print $handle "+---+\n";
951 0         0  
952 0         0 my $oidx;
953             foreach my $idx (1..$self->{sv_id}) {
954 0 0 0     0 print $handle $self->diag_sv_idx($idx);
955 0   0     0 }
956 0         0 print "-----\n" if $self->{ref_id} and $self->{sv_id};
957             foreach my $idx (1..($self->{ref_id}||0)) {
958             print $handle $self->diag_ref_idx($idx);
959 0         0  
960 0         0 }
961             print $handle "+---+\n";
962             $self;
963             }
964 4689     4689 0 7756  
965             sub remove_deref {
966 4689         7052 my $var=shift;
967 4689 100       11452  
968 220         538 my ($brace,$rest,$sigil);
969             if ($var=~s/^([\@\%\$])(?=\$)//) {
970 4469         6286 ($sigil,$brace)=($1,$var)
971 4469         17893 } else {
972             local $@;
973 4689 100 100     362007 ($brace,$rest,$sigil)= Text::Balanced::extract_bracketed( $var, '{q}',qr/[\@\%\$]/ );
974 406         1447 }
975 406 50       1600 if ($brace and !$rest) {
976             $brace=~s/^\{(.*)\}$/$1/;
977 4283         9331 return wantarray ? ($sigil,$brace) : $brace;
978             } else {
979             return;
980             }
981             }
982              
983             my %tname=qw(HASH % ARRAY @ SCALAR $ REF $);
984 5711     5711   12472  
985             sub _build_name {
986 5711 50       11500 my ( $self, $name, $type, $val ) = @_;
987 5711 50       11936  
988 5711 100       16645 $DEBUG>1 and print STDOUT " _build_name( $name '$type' => ";
    50          
989             $type=$tname{$type} if $tname{$type};
990 4579         8614 if ($type=~/[[{]/) {
991 4579         8364  
992 4579 100 100     21788 $name=~s/[\@\%]\$/\$/;
      100        
993             my ($sigil,$brace)=remove_deref($name);
994             if ( $name =~ /^([\@\%\$])(\w+)$/ or $sigil
995             or $name=~/^\*.*\{(?:SCALAR|HASH|ARRAY)\}$/
996             )
997 3243 100 66     11756 {
998              
999 3243         7385 $name .= '->' if !($name =~ s/^[\@\%]/\$/)
1000             or $sigil;
1001             $name=~s/^\$(\$.*)->$/\$\{$1\}->/;
1002 4579 50       9608 }
1003              
1004 4579 100       10207 $DEBUG>1 and print STDOUT "$name => ";
    50          
1005 2197         5020  
1006             if ( $type eq '[' ) {
1007 2382         4546 $name .= "[$val]";
1008             } elsif ( $type eq '{' ) {
1009 0         0 $name .= "{" . _quotekey($val) . "}";
1010             } else {
1011             Carp::confess "Fallen off the end of the world...";
1012 1132 100 100     4268 }
1013             } elsif ( $type =~ /^[\@\%\$]$/ ) {
1014 1132 50 66     4467 $name = "{$name}"
1015             if $name =~ /[\[\{]/ or $name=~/^\*/;
1016             $name = $type . $name
1017             unless substr( $name, 0, 1 ) eq $type and $type ne '$';
1018 24     24   278  
  24         64  
  24         212791  
1019 0         0 } else {
1020             no warnings; # XXX - why is this here? Yves
1021 5711 50       12019 Carp::confess "unimplemented _build_name";
1022 5711         15603 }
1023             $DEBUG>1 and print "$name )\n";
1024             $name;
1025             }
1026 352     352   619  
1027 352         2553 sub _reset {
1028 11353 100       26139 my $self=shift;
1029 8672         17442 foreach my $key (keys %$self) {
1030             next unless $key=~/^(sv|ref|fix|cat|type|names|reqs|cache)/;
1031 352         1256 delete $self->{$key};
1032 352         851 }
1033             $self->{sv_id}=$self->{ref_id}=0;
1034             $self;
1035             }
1036 0     0 0 0  
1037 0         0 sub diag_sv_idx {
1038 0   0     0 my $self=shift;
1039 0         0 my $idx=shift;
1040             my $prefix=shift||'';
1041             my $oidx=$self->{ref}{$self->{sva}[$idx]};
1042             my $ret=$prefix.
1043 0         0 sprintf "S%s%2d : %#x(c%2d|%2d) Dp:%2d %s Du:%s => %s %s %s %s\n",
1044             ($self->{special}{$idx} ? '*' : ' '),$idx,
1045             (map { $self->{$_}[$idx] } qw( sva svc svt svd )),
1046             ($self->{svro}[$idx] ? 'RO ' : 'RW'),
1047 0         0 (!$self->{svdu}[$idx]
1048 0         0 ? '-'
1049             : defined ${$self->{svdu}[$idx]}
1050             ? ${$self->{svdu}[$idx]}
1051             : '?'),
1052             $self->{svn}[$idx],
1053 0 0       0 (defined $self->{unames}[$idx-1] ? "($self->{unames}[$idx-1])" : ""),
    0          
    0          
    0          
    0          
    0          
    0          
1054             (($oidx) ? "< $self->{refn}[$oidx] >" : ""),
1055 0 0 0     0 ($self->{svon}{$idx} ? ": $self->{svon}{$idx}" : "")
1056 0         0 ;
1057             if ($prefix and $oidx) {
1058 0         0 $ret.=$prefix.$self->diag_ref_idx($oidx);
1059             }
1060             $ret;
1061             }
1062 0     0 0 0  
1063 0         0 sub diag_ref_idx {
1064 0         0 my $self=shift;
1065             my $idx=shift;
1066             my $oidx=$self->{sv}{$self->{refa}[$idx]};
1067             sprintf "R %2d : %#x(c%2d|%2d) Dp:%2d Du:%s => %s %s\n",
1068 0 0       0 $idx,
1069             (map {
1070             defined $self->{$_}[$idx] ? $self->{$_}[$idx] : -1
1071             } qw(refa refc reft refd )),
1072 0         0 (!$self->{refdu}[$idx]
1073 0         0 ? '-'
1074             : defined ${$self->{refdu}[$idx]}
1075 0 0       0 ? ${$self->{refdu}[$idx]}
    0          
    0          
1076             : '?'),
1077             $self->{refn}[$idx],
1078             (($oidx) ? " < $self->{svn}[$oidx] >" : "")
1079             ;
1080             }
1081              
1082              
1083             =item Dump
1084              
1085             =item Dump VALUES
1086              
1087             Smart non method based constructor.
1088              
1089             This routine behaves very differently depending on the context it is
1090             called in and whether arguments are provided.
1091              
1092             If called with no arguments it is exactly equivalent to calling
1093              
1094             Data::Dump::Streamer->new()
1095              
1096             which means it returns an object reference.
1097              
1098             If called with arguments and in scalar context it is equivalent to calling
1099              
1100             Data::Dump::Streamer->new()->Data(@vals)
1101              
1102             except that the actual depth first traversal is I until C
1103             is called. This means that options that must be provided before the
1104             C phase can be provided after the call to C. Again, it
1105             returns a object reference.
1106              
1107             If called with arguments and in void or list context it is equivelent to
1108             calling
1109              
1110             Data::Dump::Streamer->new()->Data(@vals)->Out()
1111              
1112             The reason this is true in list context is to make
1113             C do the right thing. And also that combined with
1114             method chaining options can be added or removed as required quite easily
1115             and naturally.
1116              
1117             So to put it short:
1118              
1119             my $obj=Dump($x,$y); # Returns an object
1120             my $str=Dump($x,$y)->Out(); # Returns a string of the dump.
1121             my @code=Dump($x,$y); # Returns a list of the dump.
1122              
1123             Dump($x,$y); # prints the dump.
1124             print Dump($x,$y); # prints the dump.
1125              
1126             It should be noted that the setting of C<$\> will affect the behaviour of
1127             both of
1128              
1129             Dump($x,$y);
1130             print Dump($x,$y);
1131              
1132             but it will not affect the behaviour of
1133              
1134             print scalar Dump($x,$y);
1135              
1136             B As of 1.11 Dump also works as a method, with identical properties
1137             as when called as a subroutine, with the exception that when called with
1138             no arguments it is a synonym for C. Thus
1139              
1140             $obj->Dump($foo)->Names('foo')->Out();
1141              
1142             will work fine, as will the odd looking:
1143              
1144             $obj->Dump($foo)->Names('foo')->Dump();
1145              
1146             which are both the same as
1147              
1148             $obj->Names('foo')->Data($foo)->Out();
1149              
1150             Hopefully this should make method use more or less DWIM.
1151              
1152             =cut
1153              
1154             my %args_insideout;
1155 47     47   22257  
1156 47 50       3510 sub DESTROY {
1157             my $self=shift;
1158             delete $args_insideout{Data::Dump::Streamer::refaddr $self} if $self;
1159             }
1160 34     34 1 33497  
1161 34 100 100     241 sub Dump {
1162 3         7 my $obj;
1163             if ( blessed($_[0]) and blessed($_[0]) eq __PACKAGE__ ) {
1164 34 100       112 $obj=shift;
1165 15 100 66     74 }
1166 8   66     47 if (@_) {
1167 8         33 if ( defined wantarray and !wantarray ) {
1168 8         65 $obj ||= __PACKAGE__->new();
1169             $obj->_make_args(@_);
1170 7   50     34 return $obj;
1171 7         29 } else {
1172             $obj||=__PACKAGE__;
1173             return $obj->Data(@_)->Out();
1174 19 100       71 }
1175 2         11 } else {
1176             if ($obj) {
1177 17         85 return $obj->Out();
1178             } else {
1179             return __PACKAGE__->new();
1180             }
1181             }
1182             }
1183              
1184              
1185             =item DumpLex VALUES
1186              
1187             DumpLex is similar to Dump except it will try to automatically determine
1188             the names to use for the variables being dumped by using PadWalker to
1189             have a poke around the calling lexical scope to see what is declared. If
1190             a name for a var can't be found then it will be named according to the
1191             normal scheme. When PadWalker isn't installed this is just a wrapper for
1192             L.
1193              
1194             Thanks to Ovid for the idea of this. See L for a
1195             similar wrapper around L.
1196              
1197             =cut
1198              
1199 2 50   2 1 97  
1200             sub DumpLex {
1201             if ( ! $HasPadWalker ) {
1202 0         0 #warn( "Can't use DumpLex without ".
1203             # "PadWalker v1.0 or later installed.");
1204 2         5 goto &Dump;
1205 2 50 33     11 }
1206 0         0 my $obj;
1207             if ( blessed($_[0]) and blessed($_[0]) eq __PACKAGE__ ) {
1208 2         5 $obj=shift;
1209             }
1210             my @names;
1211             # = map {
1212             # PadWalker::var_name(1,\$_)
1213             # || PadWalker::var_name(1,\$_)
1214             # (ref $_ && PadWalker::var_name(1,$_));
1215             # $str
1216             # } @_;
1217             #if ( !@names && @_ ) {
1218 2         49  
1219             my %pad_vars;
1220             foreach my $pad ( PadWalker::peek_my(1),
1221 4         20 PadWalker::peek_our(1)
1222 17   33     88 ){
1223             while (my ($var,$ref) = each %$pad) {
1224             $pad_vars{ refaddr $ref } ||= $var;
1225 2         9 }
1226 5         9 }
1227 5         10 foreach (@_) {
1228 7 100       21 my $name;
1229             INNER:foreach ( \$_, $_ ) {
1230             $name=$pad_vars{refaddr $_}
1231 5         11 and last INNER;
1232             }
1233 2 50 33     12 push @names, $name;
1234 2   33     12 }
1235 2         9 if ( defined wantarray and !wantarray ) {
1236 2         9 $obj ||= __PACKAGE__->new();
1237 2         10 $obj->_make_args(@_);
1238             $obj->Names(@names);
1239 0   0     0 return $obj;
1240 0         0 } else {
1241             $obj||=__PACKAGE__;
1242             return $obj->Names(@names)->Data(@_)->Out();
1243             }
1244             }
1245              
1246             =item DumpVars PAIRS
1247              
1248             This is wrapper around L which expect to receive
1249             a list of name=>value pairs instead of a list of values.
1250             Otherwise behaves like L. Note that names starting
1251             with a '-' are treated the same as those starting with '*' when
1252             passed to L.
1253              
1254             =cut
1255              
1256 1     1 1 3  
1257 1 50 33     6 sub DumpVars {
1258 0         0 my $obj;
1259             if ( blessed($_[0]) and blessed($_[0]) eq __PACKAGE__ ) {
1260 1 50       6 $obj=shift;
1261 0         0 }
1262 0         0 if (@_ % 2) {
1263             warnings::warnif "Odd number of arguments in DumpVars";
1264 1         3 pop @_;
1265             }
1266 1         6 my @names;
1267 3         7 my @args;
1268 3         8 for ( 0 .. $#_/2 ) {
1269             $names[$_]=$_[$_*2];
1270             $args[$_]=$_*2+1;
1271 1 50 33     9 }
1272 1   33     7 #die "@_:@names|@args";
1273 1         8 if ( defined wantarray and !wantarray ) {
1274 1         5 $obj ||= __PACKAGE__->new();
1275 1         6 $obj->_make_args(@_[@args]);
1276             $obj->Names(@names);
1277 0   0     0 return $obj;
1278 0         0 } else {
1279             $obj||=__PACKAGE__;
1280             return $obj->Data(@_[@args])->Names(@names)->Out();
1281             }
1282             }
1283              
1284 2277     2277   4635  
1285             sub _reg_ref {
1286 2277 50       4092 my ($self,$item,$depth,$name,$cnt,$arg)=@_;
1287              
1288 2277         4158 warn "_ref_ref($depth,$name,$cnt)\n" if $DEBUG;
1289 2277 100       4438  
1290 2277         3123 my $addr=refaddr $item;
1291 2277 100       5564 $arg->{raddr}=$addr if $arg;
1292 1577         3940 my $idx;
1293 1577 100       3695 unless ($idx=$self->{ref}{$addr}) {
1294 1577         3300 $idx=$self->{ref}{$addr}=++$self->{ref_id};
1295 1577         2684 $arg->{ridx}=$idx if $arg;
1296 1577         2883 $self->{refn}[$idx]=$name;
1297 1577         2573 $self->{refd}[$idx]=$depth;
1298 1577 50       5189 $self->{refa}[$idx]=$addr;
1299             $self->{refc}[$idx]=$cnt;
1300 700         1334 return wantarray ? ($idx,0) : $idx
1301 700 100       1413 }
1302 700 50       1854 $self->{reft}[$idx]++;
1303             $arg->{ridx}=$idx if $arg;
1304             return wantarray ? ($idx,1) : undef;
1305             }
1306              
1307 1548     1548   3598  
1308 1548 50       3590 sub _reg_scalar {
1309 1548         3418 my ($self,$item,$depth,$cnt,$ro,$name,$arg)=@_;
1310 1548         2396 Carp::cluck $name if $name=~/^\$\*/;
1311 1548 100       3278 my $addr=refaddr \$_[1];
1312 1548 100       3937 my $idx;
1313 1209         2954 $arg->{addr}=$addr if $arg;
1314 1209         2357 unless ($idx=$self->{sv}{$addr}) {
1315 1209         2312 $idx=$self->{sv}{$addr}=++$self->{sv_id};
1316 1209         1993 $self->{svd}[$idx]=$depth;
1317 1209         2011 $self->{sva}[$idx]=$addr;
1318 1209 100       2946 $self->{svro}[$idx]=$ro;
1319             $self->{svc}[$idx]=$cnt;
1320 1209         3440 $self->{svw}{$addr}=!0
1321 1209 100       2888 if isweak($_[1]);
1322 139         274 ($self->{svn}[$idx]=$name)=~s/^[\@\%\&]/\$/;
1323             if ($self->{svn}[$idx] ne $name) {
1324 139         381 $self->{svn}[$idx].="_"; #XXX
1325             #warn "$self->{svn}[$idx] ne $name"
1326             $self->{svon}{$idx}=$name;
1327             }
1328 339 50       748  
1329 0         0 } else{
1330 0         0 if ($DEBUG>9) {
1331             print $self->diag_sv_idx($idx);
1332             print "$name is already registered as $self->{svn}[$idx] ".
1333 339 100 100     1092 "Depth ($self->{svd}[$idx]) $depth\n";
1334 12         32 }
1335             if ($self->{svn}[$idx]=~/^\$\{?\$/ and $name!~/^\$\{?\$/) {
1336             $self->{svn}[$idx]=$name;
1337 1548         2712 }
1338 1548 100       3127 }
1339 1548 50       3374 $self->{svt}[$idx]++;
1340 1548         3306 $arg->{idx}=$idx if $arg;
1341 1548         3053 Carp::confess "Dupe name!" if $self->{svrt}{$name};
1342             $self->{svrt}{$name}=$idx;
1343             return $name;
1344             }
1345              
1346             *Precise=\&Dump;
1347              
1348 351     351   600 # we make an array of hashes containing useful info about the arguments
1349             sub _make_args {
1350             my $self=shift;
1351 351         1081 $args_insideout{refaddr $self}= [
1352 749         5016 map {
1353             {
1354             item => \$_[$_],
1355             ro => readonly($_[$_]),
1356             refcnt => sv_refcount($_[$_]),
1357             }
1358 351         1064 } 0..$#_
1359             ];
1360             return $args_insideout{refaddr $self}
1361             }
1362              
1363             =back
1364              
1365             =head2 Methods
1366              
1367             =over 4
1368              
1369             =item Data
1370              
1371             =item Data LIST
1372              
1373             Analyzes a list of variables in breadth first order.
1374              
1375             If called with arguments then the internal object state is reset before
1376             scanning the list of arguments provided.
1377              
1378             If called with no arguments then whatever arguments were provided to C
1379             will be scanned.
1380              
1381             Returns $self.
1382              
1383             =cut
1384              
1385 2260     2260   5541  
1386 2260 100       5195 sub _add_queue {
    50          
1387 2232         5788 my ($self,$queue,$type,$item,$depth,$name,$rcount,$arg)=@_;
1388             if (substr($type,0,1) ne '*') {
1389 28         60 push @$queue,[\$item,$depth,$name,$rcount,$arg];
1390 28         75 } elsif($self->{style}{dumpglob}) {
1391             local @_;
1392             foreach my $t ($self->_glob_slots('FORMAT')) {
1393              
1394             #warn $type.":$t\n";
1395             #register?
1396             #$self->_reg_scalar(*$item{$t},$depth+1,sv_refcount(*$item{$t}),
1397 140         287 # readonly(*$item{$t}),'*'.$name."{$t}");
1398 140 100       342  
1399 56 100 100     189 my $v=*$item{$t};
1400             next unless defined $v;
1401             next if $t eq 'SCALAR' and !defined($$v);
1402             push @$queue,[
1403             \*$item{$t},
1404 45         230 $depth+1,
1405             $type."{$t}",
1406             refcount(\*$item{$t})
1407             ];
1408             }
1409 2260         6268 }
1410             #use Scalar::Util qw(weaken);
1411             $self;
1412             }
1413 347     347 1 219502  
1414 347         583 sub Data {
1415 347 50       897 my $self=shift->_safe_self;
1416             my $args;
1417 347 100       918 print "Data(".scalar(@_)." vars)\n"
    50          
1418 340         1018 if $DEBUG;
1419 340         1036 if (@_) {
1420             $self->_reset;
1421 0         0 $self->_make_args(@_);
1422             } elsif ( $self->{cataloged} ) {
1423 347   33     1140 $self->_reset;
1424             }
1425 347         584 $args= $args_insideout{refaddr $self}
1426             || Carp::carp "No arguments!";
1427 347         506 my $pass=1;
  359         583  
1428 359         528 PASS:{
1429 359         827 my @queue;
1430             my $idx=0;
1431 790         1097 foreach my $arg (@$args) {
  790         2404  
1432             #($self,$item,$depth,$cnt,$ro,$name)
1433 790         2298 my $make_name=$self->_make_name(${ $arg->{item} },$idx++);
1434             my $name=$self->_reg_scalar(
1435             ${ $arg->{item} },
1436             1,
1437 790         1408 $arg->{refcnt},
1438             $arg->{ro},
1439             $make_name,
1440 790         1558 $arg
1441 790 100       1115 );
  790         2790  
1442 682         1196 $arg->{name}=$name;
1443 682         1207 if (my $type=reftype_or_glob ${ $arg->{item} }) {
  682         1908  
1444             $self->_add_queue(\@queue, $type, ${ $arg->{item} }, 2,
1445             $name, refcount ${ $arg->{item} },$arg)
1446             }
1447 359         1170 }
1448              
1449 359         0 my %lex_addr;
1450 359         0 my %lex_addr2name;
1451             my %lex_name;
1452 359         876 my %lex_special;
1453              
1454             while (@queue) {
1455             # If the scalar (container) is of any interest it is
1456             # already registered by the time we see it here.
1457 2277 50       4656 # at this point we only care about the contents, not the
1458             # container.
1459             print Data::Dumper->new([\@queue],['*queue'])->Maxdepth(3)->Dump
1460             if $DEBUG>=10;
1461              
1462             my ($ritem,
1463             $cdepth,
1464 2277         3010 $cname,
  2277         5075  
1465             $rcnt,
1466             $arg)=@{shift @queue};
1467              
1468 2277         4857  
1469              
1470 2277         3108 my ($frozen,$item,$raddr,$class);
  2281         3516  
1471 2281         4210 DEQUEUE:{
1472 2281         4117 $item=$$ritem;
1473             $raddr=refaddr($item);
1474 2281 100       5352 $class=blessed($item);
1475 1 50       5  
1476 1         3 if ($self->{ref_fz}{$raddr}) {
1477             print "Skipping frozen element $raddr\n" if $DEBUG;
1478             next;
1479             }
1480 2280 50       4201  
1481             $DEBUG and
1482 2280 50       4201 print "Q-> $item $cdepth $cname $rcnt ($raddr)\n";
1483 0 0       0  
1484             unless ($raddr) {
1485 0         0 $DEBUG and
1486             print " Skipping '$cname' as it isn't a reference.\n";
1487             next;
1488 2280 100       3905 }
1489 2276         3095  
1490 2276 100 100     12593 last DEQUEUE if $frozen;
    100 66        
      100        
1491 1 50       3 $frozen=1;
1492             if ($self->{style}{ignore}{"#$raddr"} || ($class&& $self->{style}{ignore}{".$class"})) {
1493             $DEBUG and
1494 1         2 print "Ignoring '$cname' as its class ($class) in ".
1495             "our ignore list.\n";
1496 149         329 next;
1497 149         293 } elsif ($class && !$self->{"cache_skip_freeze"}{$class}) {
1498 149 50       381 my $freezer= $self->{cache_freeze_class}{$class};
    0          
1499 149         478 my ( $proxy, $thaw, $postop );
1500             if (! defined $freezer ) {
1501             for ( $self->{style}{freeze_class}{$class},
1502             $self->{style}{freezer},
1503 440         725 'DDS_freeze' )
1504 440 100       872 {
    100          
1505 290 50       1702 $freezer= $_;
    100          
1506 0         0 if ( $freezer ) {
1507 0         0 if (ref $freezer) {
1508             eval {
1509 0 0       0 ($proxy,$thaw,$postop)= $freezer->($$ritem);
1510             };
1511 6         13 last if !$@;
1512 6         11 } elsif ( $class->can($freezer) ) {
  6         26  
1513             eval {
1514 6 50       67 ($proxy,$thaw,$postop)= ${$ritem}->$freezer();
1515             };
1516             last if !$@;
1517 1         3 }
1518             } elsif ( defined $freezer ) {
1519             last;
1520 149 100       372 }
1521 145         343 }
1522             if (! defined $proxy) {
1523 4         12 $self->{"cache_skip_freeze"}{$class}=1;
1524             } else {
1525             $self->{cache_freeze_class}{$class}= $freezer;
1526             }
1527 0         0  
1528             } elsif (ref $freezer) {
1529 0         0 ($proxy,$thaw)= $freezer->($$ritem);
  0         0  
1530             } else {
1531 149 100       347 ($proxy,$thaw)= ${$ritem}->$freezer();
1532 4         12 }
1533             if ( $thaw ) {
1534 149 50       312 $self->{ref_thaw}{$raddr}= $thaw;
1535 0         0 }
1536             if ( $postop ) {
1537 149 50       437 $self->{ref_postop}{$raddr}= $postop;
1538 149         369 }
1539 149         282 if ( refaddr($proxy) != $raddr ) {
1540 149 100       337 $self->{ref_fz}{$raddr}= $proxy;
1541 4         9 $ritem= \$proxy;
1542             if (ref $proxy) {
1543 145         301 redo DEQUEUE;
1544             } else {
1545             next;
1546             }
1547             }
1548             }
1549              
1550 2277         5019 }
1551 2277 100 33     5060  
1552             my ($idx,$dupe)=$self->_reg_ref($item,$cdepth,$cname,$rcnt,$arg);
1553             $DEBUG and print " Skipping '$cname' as it is a dupe of ".
1554             "$self->{refn}[$idx]\n"
1555 2277 50       4326 if $dupe;
1556 2277 100       4595  
1557             $DEBUG>9 and $self->diag;
1558             next if $dupe;
1559 1577         3503  
1560 1577         2889  
1561 1577         2386 my $reftype=reftype $item;
1562 1577         2368 my $cnt=refcount($item);
1563 1577 100 100     3837 my $overloaded=undef;
1564 26         748 my $isoverloaded=0;
1565 26         38 if (defined $class and overload::Overloaded($item)) {
1566 26         50 disable_overloading( $item );
1567             $overloaded= $class;
1568             $isoverloaded= 1;
1569             }
1570 1577 100 100     14226  
    100 100        
    100          
    100          
    100          
1571              
1572             if ( $reftype eq 'SCALAR' or
1573             $reftype eq 'REF' or
1574 548         1195 $reftype eq 'GLOB' )
1575 548         1277 {
1576 548 50       1118 my $name=$self->_build_name($cname,'$');
1577 548         1544 my $cnt=sv_refcount($$item);
1578             if ($cnt>1) {
1579             $self->_reg_scalar($$item,$cdepth+1,$cnt,
1580 548 100       1877 readonly($$item),$name);
1581 368         1015 }
1582             if (my $type=reftype_or_glob $$item) {
1583             $self->_add_queue(\@queue,$type,$$item,
1584             $cdepth+2,$name,$cnt)
1585             }
1586 396         1182  
1587 1136         2347 } elsif ($reftype eq 'ARRAY') {
1588 1136         2860 foreach my $idx (0..$#$item) {
1589 1136 100       2274 my $name=$self->_build_name($cname,'[',$idx);
1590 184 50       454 my $cnt=sv_refcount($item->[$idx]);
1591             if ($cnt>1) {
1592 184         593 print "refcount($name)==$cnt\n"
1593             if $DEBUG>9;
1594             $self->_reg_scalar($item->[$idx],$cdepth+1,$cnt,
1595 1136 100       3595 readonly($item->[$idx]),$name);
1596 680         1910 }
1597             if (my $type=reftype_or_glob $item->[$idx]) {
1598             $self->_add_queue(\@queue,$type,$item->[$idx],
1599             $cdepth+2,$name,$cnt)
1600             }
1601 509         952 }
1602 509         1659 } elsif ($reftype eq 'HASH') {
1603 509 50       1126 my $ik=$self->{style}{indentkeys};
1604 0         0 my ($keyary, $thaw)= $self->_get_keys($item,0,$raddr,$class);
1605             if ($thaw) {
1606 509         781 $self->{ref_thaw}{$raddr}= $thaw;
1607 509         728 }
1608 509         707 my $key_len=0;
1609 509 50 33     1944 my $key_sum=0;
1610             my $key_count=0;
1611 509 50       1685 die reftype $keyary if $keyary && reftype($keyary) ne 'ARRAY';
1612              
1613             while ( defined( my $key =
1614             defined $keyary ? $keyary->[$key_count] : each %$item
1615 1191 50       2297 ))
1616 1191         2096 {
1617 1191         2097 if ($ik) {
1618 1191 100       2677 my $qk=_quotekey($key);
1619             $key_sum+=length($qk);
1620 1191         1625 $key_len=length($qk) if $key_len
1621 1191         2468 }
1622 1191         3007 $key_count++;
1623 1191 100       2363 my $name=$self->_build_name($cname,'{',$key);
1624             my $cnt=sv_refcount($item->{$key});
1625 26         95 if ($cnt>1) {
1626             $self->_reg_scalar($item->{$key},$cdepth+1,$cnt,
1627 1191 100       4573 readonly($item->{$key}),$name);
1628 500         1451 }
1629             if (my $type=reftype_or_glob $item->{$key}) {
1630             $self->_add_queue(\@queue,$type,$item->{$key},
1631             $cdepth+2,$name,$cnt);
1632 509 100       1432 }
1633 509 50 66     1648 }
1634             my $avg=$key_count>0 ? $key_sum/$key_count : 0;
1635 509         1523 $self->{ref_hklen}{$raddr}=($key_len>8 && (2/3*$key_len)>$avg)
1636             ? int(0.5+$avg) : $key_len;
1637             $self->{ref_hkcnt}{$raddr}=$key_count;
1638             #warn "$raddr => $key_count";
1639 68 100       143  
1640             } elsif ($reftype eq 'CODE') {
1641 40         93 if ($pass == 1) {
1642              
1643 40         124 my $used=_get_lexicals($item);
1644 78 100       257  
1645 39         87 foreach my $name (keys %$used) {
1646 39 100       92 next unless $name=~/\D/;
1647 30         68 my $addr=refaddr($used->{$name});
1648 30 100       56 if ( !$lex_addr{$addr} ) {
1649             $lex_addr{$addr}=$used->{$name};
1650             if ( $lex_name{$name} ) {
1651             my $tmpname=sprintf "%s".$self->{style}{eclipsename},
1652             substr($name,0,1),
1653             $self->{style}{eclipsename}=~/^[^%]*%s/
1654 7 100       84 ? ( substr($name,1),
1655             ++$lex_special{$name}, )
1656 7         26 : ( ++$lex_special{$name},
1657 7         25 substr($name,1), );
1658             $lex_name{$tmpname}=$addr;
1659 7         32 $lex_addr2name{$addr}=$tmpname;
1660             $self->_add_queue(\@queue,reftype_or_glob $used->{$name},
1661 23         45 $used->{$name},$cdepth+1,$tmpname,2);
1662 23         39 } else {
1663             $lex_name{$name}=$addr;
1664 23         86 $lex_addr2name{$addr}=$name;
1665             $self->_add_queue(\@queue,reftype_or_glob $used->{$name},
1666             $used->{$name},$cdepth+1,$name,2);
1667             }
1668             }
1669             }
1670             }
1671             } elsif ($reftype eq 'FORMAT') {
1672             # Code similar to that of CODE should go here I think.
1673             } else {
1674 51 50       196 # IO?
1675             Carp::confess "Data() can't handle '$reftype' objects yet ($item)\n :-(\n"
1676 1577 100       5047 if $ENV{DDS_STRICT};
1677 26         56 }
1678             if ($isoverloaded) {
1679             restore_overloading( $item, $overloaded );
1680 359 100       938 }
1681             }
1682 347         587 if ( $pass++ == 1 ) {
1683 347         551  
  347         1521  
1684 744         1733 my %items;
1685 744         1901 for my $idx ( 0..$#{$args_insideout{refaddr $self}} ) {
1686             my $item=$args_insideout{refaddr $self}[$idx];
1687             $items{ refaddr $item->{item} } = $idx;
1688 347         651 }
1689 347         536  
1690 347         584 my @add;
1691             my $added=0;
1692             if (0) {
1693 347         862 @add=keys %lex_addr;
1694 30 100       51 } else {
1695 3         8 for my $addr (keys %lex_addr) {
1696 3 100       10 if ( exists $items{$addr} ) {
1697 2         9 my $idx = $items{$addr};
1698 2         6 if ( !$self->{unames}[$idx] ){
  2         11  
1699             for ($self->{unames}[$idx] = $lex_addr2name{$addr}) {
1700 2         5 s/^[^\$]/*/; s/^\$//;
1701             }
1702 1         2 $added++;
1703 1         3 } else {
1704 1         6 my $new=$self->{unames}[$idx];
  1         5  
1705 1         3 my $old=$lex_addr2name{$addr};
1706 1         2 $new=~s/^(\*)?/substr($old,0,1)/e;
1707 1         4 delete $lex_name{$lex_addr2name{$addr}};
1708             $lex_addr2name{$addr}=$new;
1709             $lex_name{$self->{unames}[$idx]} = $addr; # xxx
1710 27         49 }
1711             } else {
1712             push @add,$addr;
1713             }
1714 347         801 }
  25         54  
1715             }
1716             @add=sort {$lex_addr2name{$a} cmp $lex_addr2name{$b}} @add;
1717 347         1463  
1718             $self->{lexicals}={
1719             a2n => \%lex_addr2name,
1720             name => \%lex_name
1721 347 100       1650 };
    100          
1722 11         35  
1723             if (@add) {
1724 11         17 unshift @{$args_insideout{refaddr $self}},
  27         72  
1725 27         36 map {
1726 27 100 66     85 my $rt=reftype($lex_addr{$_});
      100        
1727 3         6 my $item;
1728             if ($rt ne 'SCALAR' and $rt ne 'GLOB' and $rt ne 'REF') {
1729 24         36 $item=\$lex_addr{$_};
1730             } else {
1731             $item=$lex_addr{$_};
1732             }
1733             {
1734             item => $item,
1735 27         101 usemy => 1,
1736             ro => 0,
1737             refcnt => refcount($lex_addr{$_}),
1738 11         23 }
  27         71  
1739 11         27 } @add;
1740             $self->{lexicals}{added}={ map { $lex_addr2name{$_} => 1 } @add };
1741 11         25 unshift @{$self->{unames}},
  27         63  
1742 27         68 map {
1743 27         71 (my $n=$lex_addr2name{$_})=~s/^[^\$]/*/;
1744             $n=~s/^\$//;
1745 11         33 $n
1746 11         45 } @add;
1747             $self->_reset;
1748 1         4 redo PASS;
1749 1         4 } elsif ($added) {
1750             $self->_reset;
1751             redo PASS;
1752             }
1753 347         742 }
1754 347         1332 }
1755             $self->{cataloged}=1;
1756             return $self;
1757             }
1758 519     519   1457  
1759             sub _add_fix {
1760             my ($self,@args)=@_;
1761             # 'var','glob','method call','lock','ref','sv','#'
1762 519 50       1750 # TODO
1763 519 50       2374 # add a fix statement to the list of fixes.
1764 0         0 my $fix=@args==1 ? shift @args : [@args];
1765             unless ($fix->[0]=~/^(var|glob|thaw|ref|sv|#|sub call|lock|bless)$/) {
1766 519 50       1221 Carp::confess "Unknown variant:".Dumper($fix);
1767 0         0 }
  0         0  
1768             if ($args[0] eq 'var') {
1769 519         765 unshift @{$self->{fix}},$fix;
  519         1671  
1770             } else {
1771             push @{$self->{fix}},$fix;
1772             }
1773             }
1774 56     56   114  
1775             sub _glob_slots {
1776             my ($self,$inc_format)=@_;
1777             # $inc_format is for a special case.
1778             return (
1779             qw(SCALAR HASH ARRAY),
1780             (($self->{style}{deparse} && $self->{style}{deparseglob})
1781 56 50 33     484 ? 'CODE' : ()),
    100 33        
1782             (($inc_format && $self->{style}{deparse} && $self->{style}{deparseglob})
1783             ? 'FORMAT' : () )
1784             );
1785             }
1786 1120     1120   2279  
1787             sub _dump_apply_fix { #handle fix statements and GLOB's here.
1788             my ($self,$isfinal)=@_;
1789             # go through the fix statements and out any that are
1790             # now fully dumped.
1791             # currently the following types are grokked:
1792 1120         1669 # 'var','glob','method call','tlock','ref','sv','#'
1793              
1794 1120         1638 my @globs;
  1146         1756  
1795 1146         2286 GLOB:{
1796 957         1400 @globs=();
1797 957         1312 @{$self->{fix}}=grep {
1798 957 50       1922 my $keep=1;
1799 957         2093 my $fix=$_;
1800             if (ref $fix) {
1801 957 50       3251 my ($type,$lhs,$rhs,$class)=@$fix;
    100          
    100          
    100          
    100          
    100          
    100          
    50          
    50          
1802 0         0  
1803 0         0 if ($type eq '#') {
1804             $self->{fh}->print(map "# $_\n",@$fix[0..$#$fix]);
1805 71 100       141 $keep=0;
1806 26         47 } elsif ($type eq 'bless') {
1807             if ($isfinal) { # $self->{"refdu"}[$lhs]
1808             $lhs=$self->{"refn"}[$lhs];
1809 26         81 $self->{fh}->print(
1810             substr($self->{style}{bless},0,-1)," ",$lhs,", ",
1811 26         59 _quote($rhs)," ",substr($self->{style}{bless},-1),
1812             ";\n");
1813             $keep=0;
1814             }
1815 290         488 } elsif ($type eq 'sv') {
1816 290 100 66     880  
  110         369  
1817 110         241 my $dref=$_->[-1];
1818 110         232 if ($self->{$type."du"}[$rhs] and ${$self->{$type."du"}[$rhs]}) {
1819 110 50       272 $rhs=$self->{$type."n"}[$rhs];
1820 110         226 my ($sigil,$var)=remove_deref($lhs);
1821 110         210 if ($sigil) {
1822             $rhs="\\".$rhs;
1823 110         499 $lhs=$var;
1824 110 50       374 }
1825 110         216 $self->{fh}->print("$lhs = $rhs;\n");
1826             $$dref=1 if ref $dref;
1827             $keep=0
1828             }
1829 436 100 100     1262 } elsif ($type eq 'ref') {
  360         1162  
1830              
1831 275         584 if ($self->{$type."du"}[$rhs] and ${$self->{$type."du"}[$rhs]}) {
1832              
1833 275 100       836 $rhs=$self->{$type."n"}[$rhs];
1834 36         76  
1835 36 100       123 if ($rhs=~/^[\@\%\&]/) {
1836             $rhs="\\".$rhs;
1837             $rhs="bless( $rhs, "._quote($class).' )'
1838 275         1098 if $class;
1839 275         577 } # Warn if
1840             $self->{fh}->print("$lhs = $rhs;\n");
1841             $keep=0
1842 8 50 33     25 }
  8         23  
1843 8         16 } elsif ($type eq 'lock') {
1844             if ($self->{refdu}[$lhs] and ${$self->{"refdu"}[$lhs]}) {
1845             $lhs=$self->{"refn"}[$lhs];
1846 8 100       44 $self->{fh}->print(@$rhs ? "lock_keys_plus( $lhs, "
  8         14  
1847             : "lock_keys( $lhs ",
1848 8         21 join(", ",map{ _quote($_) } @$rhs),
1849             ");\n");
1850             $keep=0;
1851             }
1852 7 100       19 } elsif ($type eq 'thaw') {
1853             # these have to happen at the end.
1854 3         5 if ($isfinal) {
  3         8  
1855 3         7 #if ($self->{refdu}[$lhs] and ${$self->{"refdu"}[$lhs]}) {
1856 3         12 ${$self->{refdu}[$lhs]}=1;
1857 3 50       23 $lhs=$self->{"refn"}[$lhs];
1858 3 100       12 my @args=@$_[3..$#$_];
1859 1         10 if ($rhs=~/^(->)?((?:\w*::)*\w+)(\(\))?$/) {
1860             if ($3) {
1861 2         19 $self->{fh}->print("$2( ".join(", ",$lhs,@args)." );\n");
1862             } else {
1863             $self->{fh}->print("$lhs->$2(".join(", ",@args).");\n");
1864 0         0 }
1865 0         0 } else {
1866             $rhs=~s/^\t//mg;
1867 3         9 $self->{fh}->print("for ($lhs) {\n$rhs\n}\n");
1868             }
1869             $keep=0;
1870 28         60 }
1871 28         58 } elsif ($type eq 'glob') {
1872             push @globs,$_;
1873 0         0 $keep=0;
1874 0 0       0 } elsif ($type eq 'var') {
1875             $rhs="\\".$rhs;
1876 0 0       0 $rhs="bless( $rhs, "._quote($class).' )'
1877 0         0 if $class;
1878             $self->{fh}->print(($self->{style}{declare} ? 'my ' : ""),"$lhs = $rhs;\n");
1879 117 100 66     207 $keep=0;
  551         1379  
1880 117 100       289 } elsif ($type eq 'sub call') {
1881 69 100       135 my @r=grep { ref $_ and (!$self->{svdu}[$$_] or !${$self->{svdu}[$$_]}) } @$fix;
  311         678  
1882 69         378 unless (@r) {
1883 69         179 my ($type,$sub,@args)=map { ref $_ ? $self->{svn}[$$_] : $_ } @$fix;
1884             $self->{fh}->print("$sub(",join(", ",@args),");\n");
1885             $keep=0;
1886 0         0 }
1887             } else {
1888             die "Bad fix: ",Dumper($fix);
1889             }
1890 957         1968  
1891 1146         1586 }
  1146         2424  
1892 1146         2332 $keep;
1893 28         80 } @{$self->{fix}};
1894 28 50 33     69 foreach my $glob (@globs) {
1895 28         52 my ($type,$lhs,$rhs,$depth,$name)=@$glob;
1896 28 100       67 print "Symbol: $name\n" if $DEBUG and $name;
1897 28         51 local @_;
1898 28         45 $name=$name ? '*'.$name : $rhs;
1899 28 100 66     107 my $overloaded=undef;
1900             my $isoverloaded=0;
1901             if (defined( blessed $lhs ) and
1902 3         93 overload::Overloaded( $lhs ) )
1903 3         9 {
1904 3         5 $overloaded=blessed $lhs;
1905             disable_overloading( $lhs );
1906 28         95 $isoverloaded=1;
1907             }
1908 112         250 foreach my $t ($self->_glob_slots(''))
1909             {
1910 112 100 100     416 my $v=*$lhs{$t};
      100        
1911              
1912             if ( not(defined $v) or
1913 68         129 ($t eq 'SCALAR' and !defined($$v)))
1914             {
1915             next;
1916             }
1917 44         66  
1918              
1919             my $dumped=0;
1920 44         118  
1921 44         100  
1922 44 50 66     131 my $gaddr=refaddr(*$lhs{$t});
1923             my $gidx=$self->{ref}{$gaddr};
1924 0         0 unless ($gidx) {
1925             next
1926             } elsif ($self->{refd}[$gidx]<$depth+1) {
1927             $self->_add_fix('ref',$name,$gidx,blessed(*$lhs{$t}));
1928             next;
1929 27 50       151 }
1930 27         114  
1931 27 50       72 $self->{fh}->print("$name = ") unless $self->{style}{terse};
1932             my $ret=$self->_dump_sv(*$lhs{$t},$depth,\$dumped,$name,length($name)+3);
1933 27         92 Carp::confess "\nUnhandled alias value '$ret' returned to _dump_apply_fix()!"
1934 27         56 if $ret;
1935             $self->{fh}->print(";\n");
1936             $dumped=1;
1937 28 50 33     166 }
1938              
1939             if ($self->{style}{deparse} && $self->{style}{deparseglob}
1940             #and defined *$lhs{FORMAT}
1941             ) {
1942             # from link from [ysth]: http://groups.google.com/groups?selm=laUs8gzkgOlT092yn%40efn.org
1943             # translate arg (or reference to it) into a B::* object
1944              
1945             # To work-around perl commit
1946             # 2acc3314e31a9342e325f35c5b592967c9850c9b, keep the
1947 28         98 # value \*$lhs alive while we inspect it as a B object
1948 28         127 # or else it'll be reaped while we're using it.
1949             my $lhs_glob = \*$lhs;
1950             my $Bobj = B::svref_2object($lhs_glob);
1951 28 50       147  
1952             # if passed a glob or globref, get the format
1953 28 100       92 $Bobj = B::GV::FORM($Bobj) if ref $Bobj eq 'B::GV';
1954 1         7  
1955 1         5 if (ref $Bobj eq 'B::FM') {
1956 1         78 (my $cleaned=$name)=~s/^\*(::)?//;
1957             $self->{fh}->print("format $cleaned =\n");
1958 1         2326 my $deparser = Data::Dump::Streamer::Deparser->new();
1959             $self->{fh}->print(
1960 1         5 $deparser->indent($deparser->deparse_format($Bobj))
1961             );
1962             $self->{fh}->print("\n");
1963 28 100       91 }
1964 3         8 }
1965             if ($isoverloaded) {
1966             restore_overloading( $lhs, $overloaded );
1967             }
1968              
1969 1146 100       3110  
1970             }
1971             redo GLOB if @globs;
1972             }
1973             }
1974              
1975             =item Out
1976              
1977             =item Out VALUES
1978              
1979             Prints out a set of values to the appropriate location. If provided a list
1980             of values then the values are first scanned with C and then
1981             printed, if called with no values then whatever was scanned last with
1982             C or C is printed.
1983              
1984             If the C attribute was provided then will dump to whatever object
1985             was specified there (any object, including filehandles that accept the
1986             print() method), and will always return $self.
1987              
1988             If the C attribute was not provided then will use an internal
1989             printing object, returning either a list or scalar or printing to STDOUT
1990             in void context.
1991              
1992             This routine is virtually always called without arguments as the last
1993             method in the method chain.
1994              
1995             Dump->Arguments(1)->Out(@vars);
1996             $obj->Data(@vars)->Out();
1997             Dump(@vars)->Out;
1998             Data::Dump::Streamer->Out(@vars);
1999              
2000             All should DWIM.
2001              
2002             =cut
2003              
2004             #
2005             # Out is just a wrapper. The overall dumping process works like this:
2006             #
2007             # Out
2008             # foreach root value
2009             # _dump_sv
2010             # _dump_rv if ref
2011             # (optionally one of)
2012             # _dump_array
2013             # _dump_hash
2014             # _dump_code
2015             # _dump_qr
2016             # _dump_apply_fix
2017             # (which may call)
2018             # _dump_sv
2019             #
2020             # _dump_array, _dump_hash, _dump_rv if needed may also call _dump_sv
2021             #
2022             # essentially _dump_sv and _dump_rv handle uniqueness checks for scalars,
2023             # and refs. _dump_sv handles the SV's containers and _dump_rv
2024             # handles the things that the SV contains a reference to. _dump_sv also
2025             # handles simple values and globs, and works with _dump_rv to handle
2026             # references to scalars correctly. If "fix" statements are required
2027             # to complete the definition of the structure (self referential structures)
2028             # then _add_fix adds them to the list, and _dump_apply_fix pulls them off.
2029             # note that _dump_apply_fix can also call _dump_sv if needed (to handle globs),
2030             # and will also emit fix statements as early as possible. no require/use
2031             # logic is currently in place. its the evalers responsibility to use the mod
2032             # w/the right tags for now...
2033 348     348 1 1885  
2034 348         924 sub Out {
2035 348 50       806 local($\,$",$,)=("","",""); # prevent globals from messing with our output via print
2036             my $self = shift->_safe_self;
2037 348 100 66     1927 print "Out(".scalar(@_)." vars)\n"
      66        
2038 7         30 if $DEBUG;
2039             if ( !$self->{in_printit} and (@_ or !$self->{cataloged} )) {
2040             $self->Data(@_);
2041 348         612 }
2042 348 50       838  
2043 348 50       724 my $fh;
2044             unless ( $self->{fh} ) {
2045 348 50       750 print " no filehandle using "
2046 348 100       928 if $DEBUG;
2047 348 50       686 if (defined wantarray) {
2048             my $class= __PACKAGE__ . (wantarray ? "::_::ListPrinter" : "::_::StringPrinter");
2049 348 50       1617 print $class,"\n"
2050             if $DEBUG;
2051 348         888 $fh = $class->new()
2052             or Carp::confess "$class failed to build!";
2053 0 0       0 $self->{'return'} = $fh;
2054 0         0 } else {
2055             print "STDOUT\n" if $DEBUG;
2056 348         711 $fh = \*STDOUT;
2057             }
2058             $self->{fh} = $fh;
2059             }
2060             # loop over the list
2061             # and dump out each one in turn
2062 348         877 # handling any potential fixes after
2063 348         767 # each definition is complete
2064 348         746 $self->{out_names}=[];
2065 348 50       821 $self->{declare}=[];
2066             $self->{special}={};
2067 348         508 $DEBUG>9 and $self->diag;
  348         1194  
2068              
2069 348         636 my @items=@{$args_insideout{refaddr $self}};
2070              
2071 348         516 my $namestr="";
  348         854  
  772         1926  
2072 348         641  
  348         783  
  772         1494  
2073             push @{$self->{out_names}},map{$_->{name}}@items; #must
2074 348 50       890 push @{$self->{declare}},map{$_->{name}}@items;
2075              
2076 0 0       0 if ($self->{style}{special}) {
2077              
2078 0         0 warn DDumper(\@items) if $DEBUG;
  0         0  
2079              
2080 0         0 $namestr="# (".join (", ",@{$self->{out_names}}).")\n";
2081              
2082             @items=sort { $self->{svc}[$b->{idx}] <=> $self->{svc}[$a->{idx}]||
2083 0 0       0 ($b->{raddr} ? $self->{refc}[$b->{ridx}] : 0)
    0          
    0          
2084             <=>
2085             ($a->{raddr} ? $self->{refc}[$a->{ridx}] : 0)
2086             } @items;
2087              
2088              
2089 0 0       0  
2090              
2091             warn DDumper(\@items) if $DEBUG;
2092 348 50 66     874 }
2093 2         10  
2094 2 50       22 if ($self->{style}{compress} && $self->{style}{compressor}) {
2095             my $prelude=$self->{style}{compressor}->();
2096             $self->{fh}->print($prelude) if $prelude;
2097 11         82 }
2098 348 100       806  
2099             $self->{fh}->print("my (",join(",",sort keys %{$self->{lexicals}{added}}),");\n")
2100 348         676 if $self->{lexicals}{added};
2101 772         1150  
2102 772         1109 foreach my $item (@items) {
  772         2416  
2103 772 50       1556 my $dumped=0;
2104             my $ret=$self->_dump_sv(${$item->{item}},1,\$dumped,$item->{name});
2105 772         2278 Carp::confess "\nUnhandled alias value '$ret' returned to Out()!"
2106 772         1165 if $ret;
2107 772         1702 $self->{fh}->print(";\n");
2108             $dumped=1;
2109 348         920 $self->_dump_apply_fix();
2110 348 50       741 }
2111             $self->_dump_apply_fix('final');
2112 348 50       744 $self->{fh}->print($namestr) if $namestr;
2113              
2114 348 50 33     1468 $self->diag if $DEBUG;
2115 348         784 #warn "@{$self->{out_names}}";
2116 348         649 if ( $self->{return} and defined wantarray) {
2117 348         1084 my $r = delete $self->{return};
2118             delete $self->{fh};
2119 0         0 return $r->value;
2120             } else {
2121             return $self;
2122             }
2123              
2124             }
2125              
2126              
2127 2     2 0 13 # sqz(str,begin,end)
2128 2         7 sub sqz {
2129 2         10 require Compress::Zlib;
2130 2 50       510 require MIME::Base64;
2131             my $res= Compress::Zlib::compress($_[0],9);
2132             return $_[1]
2133             ? $_[1]
2134             . MIME::Base64::encode($res,"")
2135             . $_[2]
2136             : MIME::Base64::encode($res,"");
2137             }
2138              
2139 0     0 0 0 # usqz(str)
2140             sub usqz {
2141             return Compress::Zlib::uncompress(
2142             MIME::Base64::decode($_[0])
2143             );
2144             }
2145              
2146              
2147 3564     3564   8512  
2148             sub _dump_sv {
2149 3564         5927 my ($self,$item,$depth,$dumped,$name,$indent,$is_ref)=@_;
2150              
2151 3564         7943 $self->{do_nl}=0;
2152 3564         6982  
2153 3564         5033 my $addr=refaddr(\$_[1]);
2154 3564 50 0     6866 my $idx=$self->{sv}{$addr};
2155             my $ro;
2156             $DEBUG and printf "_dump_sv %d %s %#x - %d\n",$depth, $name,$addr,$idx||0;
2157 3564   66     6545  
2158 3564         8779  
2159 3564         6630 $name||=$self->{svn}[$idx];
2160 3564 100       6415 (my $clean_name=$name)=~s/^[\@\%\&](\w+)/\$${1}_/; # XXX
2161             my $optspace=$self->{style}{optspace};
2162             if ($idx) {
2163              
2164 1491         2698 # Its a monitored scalar.
2165              
2166             my $pre_dumped=$self->{svdu}[$idx];
2167 1491   66     6547 my $name_diff=(
2168             $self->{svd}[$idx]==$depth
2169             and $self->{svn}[$idx] ne $clean_name
2170             and $clean_name!~/\*/
2171             and $name!~/^\&/
2172             );
2173              
2174             #print "Idx: $idx Special keys:",join("-",keys %{$self->{special}}),"\n"
2175 1491 50       2834 # if $DEBUG and keys %{$self->{special}};
2176              
2177             print "sv_dump Monitored:\n",$self->diag_sv_idx($idx," ") if $DEBUG;
2178 1491 100 100     7863  
    100 100        
      100        
2179              
2180             if (( $pre_dumped and !$self->{svon}{$idx})
2181             or (!$self->{svon}{$idx} ? ($self->{svd}[$idx]<$depth or $name_diff) : undef) )
2182             {
2183 316 0 33     671  
      0        
      0        
2184             print "PREDUMPED: $self->{svon}{$idx}\n"
2185             if $DEBUG and $self->{svon}{$idx} and $pre_dumped and $$pre_dumped;
2186              
2187 316 0       613 # We've seen it before.
    50          
2188             # Unless its a ref it must be an alias
2189             print(($name_diff ? "Name diff" : "No name diff"), " $name, $clean_name","\n")
2190 316         720 if $DEBUG;
2191              
2192 316 100       639 my ($str,$ret)=('',undef);
2193 220 100 100     1113  
      100        
      100        
2194             if ($is_ref) {
2195             if ($self->{svd}[$idx]==1 && !$self->{style}{declare}
2196 104         228 || ($pre_dumped && $$pre_dumped)
2197             ) {
2198             $str="\\$self->{svn}[$idx]";
2199             } else {
2200             #see the 'Many refs' tests in t\dump.t for
2201             #why this is here. basically we need to
2202             #ensure the ref is modifiable. If its two $'s
2203 116 100       259 #then its modifiable anyway, more and it wont be.
2204 6         21 # $ref=\\$x; $ref=RW $$ref=RO $$$ref=$x=RW
2205             unless ($self->{style}{purity}) {
2206 110         246 $str="\\$self->{svn}[$idx]";
2207 110 100       232 } else {
2208 4         14 my $need_do=($name=~/^\$\$\$+/);
2209             if ($need_do) {
2210             $str.=join($optspace,qw( do { my $f = ),'');
2211             }
2212 110 50       544  
    50          
2213             $str.=!$self->{style}{verbose}
2214 110         203 ? "'R'" : _quote($DEBUG ? 'SR: ' : 'R: ',
  110         281  
2215 110         423 "$self->{svn}[$idx]");
2216             $ret=\do{my $nope=0};
2217 110 100       292 $self->_add_fix('sv',$name,$idx,$ret);
2218              
2219             $str.="$optspace}" if ($need_do)
2220             }
2221 96 100       255 }
    100          
2222 36 50       93 } else {
2223 0         0 if ($depth==1) {
2224             if ($self->{style}{declare}) {
2225             $str.="my $name;\n";
2226             }
2227 36         103 #push @{$self->{out_names}},$name;
2228             #push @{$self->{declare}},$name;
2229 52 50       176 $str.="alias_ref(\\$name,\\$self->{svn}[$idx])";
2230 52         115 } elsif ($self->{style}{purity}) {
2231             $str.=!$self->{style}{verbose} ? "'A'" : _quote("A: ",$self->{svn}[$idx]);
2232 8         19 $ret=\$idx;
2233 8         16 } else {
2234             $str.="alias_to($self->{svn}[$idx])";
2235             $ret='';
2236 316         636 }
2237 316 50       780 }
2238 316         1194 $self->{buf}+=length($str);
2239 316 100       1060 $self->{buf}=length($1) if $str=~/\n([^\n]*)\s*\z/;
2240             $self->{fh}->print($str);
2241             return $ret ? $ret : ()
2242 1175   66     4789 } else {
2243             # we've never seen it before and we need to dump it.
2244             $self->{svdu}[$idx]||=$dumped;
2245 1175 0 33     2261  
2246             print "Defining Special:".$self->diag_sv_idx($idx)
2247 1175 50       2365 if $DEBUG and $self->{special}{$idx};
2248 1175 50       2402  
2249             $self->{svn}[$idx]=$name if $self->{special}{$idx};
2250             $self->{svd}[$idx]=$depth if $self->{special}{$idx};
2251 1175         2212  
2252             }
2253 2073 50       5763 $ro=$self->{svro}[$idx];
2254             } else {
2255 3248 50       5928 $ro=readonly $_[1] unless defined $ro;
2256 3248 100       6623 }
2257             print "sv_dump: Postindexed\n" if $DEBUG;
2258 736 50 66     2170 if ($depth==1) {
      66        
2259             # root level object. declare it
2260 139 50       301 if ($name ne $clean_name and $name!~/^\*/ and $self->{svc}[$idx]>1) {
2261 139         297  
2262 139 100       271 print "Special $name\n" if $DEBUG;
2263             my $oidx=$self->{ref}{$self->{sva}[$idx]};
2264 19         56 if ($oidx) {
2265 19         49 #theres a ref to us out there
2266 19 50       52 my $name=$self->_build_name($self->{refn}[$oidx],'$');
2267             $self->{svn}[$idx]=$name;
2268             print "Oindex! $oidx $name\n" if $DEBUG;
2269             #$self->{svd}[$idx]=$self->{refd}[$idx]+1;
2270             }
2271 139         220  
2272             #$self->{special}{$idx}++;
2273 139 50       281 $self->{svdu}[$idx]=undef;
2274              
2275             print $self->diag_sv_idx($idx,1) if $DEBUG;
2276             }
2277 736 100 66     2844 #push @{$self->{out_names}},$name; #must
2278             #push @{$self->{declare}},$name;
2279 732 100 66     3665 unless ($self->{style}{terse} || $name=~/^\&/) { # XXX
2280             my $str=(($self->{style}{declare} && $name!~/^\*/
2281             && !$self->{lexicals}{added}{$name}
2282 732         2597 ) ? "my$optspace" : ""
2283 732         1306 )."$name$optspace=$optspace";
2284 732         1238 $self->{fh}->print($str);
2285             $indent=length($str);
2286 4         8 $self->{buf}=0;
2287             } else {
2288 736 50       1494 $indent=0;
2289             }
2290             print "toplevel\n" if $DEBUG;
2291 3248         6097 }
2292              
2293 3248 100       6694 my $iaddr=refaddr $item;
2294              
2295             $self->{fh}->print("\\")
2296 3248         6769 if $is_ref;
2297              
2298             my $glob=globname $item;
2299             my $add_do=$self->{style}{purity}
2300             && !$ro
2301             && $is_ref
2302 3248   100     15961 && !blessed($_[1])
2303             && !$glob
2304             && do {
2305             my $rtype= reftype($_[1]);
2306             $rtype eq "" or
2307             ($rtype eq "SCALAR" and ( $] < 5.020 or !readonly(${ $_[1] }) ) )
2308             }
2309             ;
2310 3248 100       6222  
2311              
2312 35         180 if ($add_do) {
2313 35         70 #warn "\n!$ro && $is_ref && !blessed($_[1]) && !$glob";
2314             $self->{fh}->print(join $optspace,qw(do { my $v = ),'');
2315             $self->{buf}+=13;
2316 3248 100       5690 }
2317 1250 50       2298  
2318 1250 100       2244 unless ($iaddr) {
2319 116         401 print "iaddr $glob\n" if $DEBUG;
2320 116         216 unless (defined $item) {
2321             $self->{fh}->print('undef');
2322 1134   100     3763 $self->{buf}+=5;
2323 1134 100 100     2429 } else {
      66        
2324 1         6 my $is_ro=($self->{style}{ro} && $ro && !$is_ref);
2325             if ($is_ro and !$self->{style}{purity} and !$self->{style}{terse}) {
2326 1134 100       1973 $self->{fh}->print("make_ro($optspace");
2327 20 100       60 }
2328 1         5 if ($glob) {
2329             if ($glob=~/^\*Symbol::GEN/) {
2330             $self->_dump_symbol($_[1],$name,$glob,'deref',$depth);
2331 19         42 } else
2332 19         64 {
2333 19 50 33     131 $self->{buf}+=length($glob);
2334             $self->{fh}->print($glob);
2335 19         69 if ($self->{style}{dumpglob} and
2336             !$self->{sv_glob_du}{$glob}++) {
2337             $self->_add_fix('glob',$_[1],$glob,$depth+1);
2338             }
2339 1114         1589 }
2340 1114 100       2246 } else {
2341 24     24   258 my $quoted;
  24         58  
  24         23350  
2342 1112 100 100     3081 if ($self->{style}{dualvars}) {
      66        
2343 2         10 no warnings 'numeric'; # XXX: is this required?
2344             if (_could_be_dualvar($item) && 0+$item ne $item && "$item" != $item ) {
2345             $quoted="dualvar( ".join(",$optspace",0+$item,_quote("$item"))."$optspace)";
2346             }
2347 1114 100       2086 }
2348 1112         1788 # XXX main scalar output here!
2349             if ( ! $quoted ) {
2350 1112 100 66     2588 my $style= $self->{style};
      33        
2351              
2352             if ( $style->{compress} &&
2353             $style->{compressor} &&
2354 2         8 length($_[1]) > $style->{compress}
2355             ){
2356 1110         2090 $quoted= $style->{compressor}->($_[1],$self);
2357             } else {
2358             $quoted=_quote($item);
2359             }
2360 1114         2135  
2361 1114 50       2580 }
2362 1114         3289 $self->{buf}+=length($quoted);
2363             $self->{buf}=length($1) if $quoted=~/\n([^\n]*)\s*\z/;
2364 1134 50       2700 $self->{fh}->print($quoted); #;
2365 1134 100 100     3262 }
    100          
2366 9         31 if( !$self->{style}{terse} ) {
2367             if ($is_ro && $self->{style}{purity}) {
2368 1         5 $self->_add_fix('sub call','make_ro',$name);
2369             } elsif ($is_ro) {
2370             $self->{fh}->print("$optspace)");
2371             }
2372             }
2373 1250         1958 #return
2374             }
2375 1998         3159 $self->{do_nl}=0;
2376 1998   100     7244 } else {
2377             $self->{do_nl}=1;
2378 3248 100       6134 $self->_dump_rv($item,$depth+1,$dumped,$name,$indent,$is_ref && !$add_do);
2379             }
2380             $self->{fh}->print("$optspace}")
2381 3248 100       6596 if $add_do;
2382             $self->_add_fix('sub call','weaken',$name)
2383 3248         6600 if $self->{svw}{$addr};
2384             return
2385             }
2386 1796     1796   3953  
2387 1796         4440 sub _brace {
2388             my ($self,$name,$type,$cond,$indent,$child)=@_;
2389 1796 100       4505 my $open=$type=~/[\{\[\(]/;
    100          
2390              
2391             my $brace= $name !~ /^[%@]/
2392             ? $type
2393             : $type =~ /[\{\[\(]/
2394 1796 100       3776 ? '('
2395 1796 100       3070 : ')';
2396             $child= $child ? $self->{style}{optspace} : "";
2397 982 100       2136 if ( $cond ) {
2398 982 100       4685 $_[-2] += $open ? $self->{style}{indentcols}
    100          
2399             : -$self->{style}{indentcols};
2400             $self->{fh}->print($open ? "" : "\n".(" " x $_[-2]),
2401             $brace,
2402 814 100       2912 $open ? "\n".(" " x $_[-2]) : "");
    100          
2403             } else {
2404             $self->{fh}->print($open ? "" : $child ,
2405             $brace,
2406             $open ? $child : "");
2407 1796         3508 }
2408             return
2409             }
2410 49     49   115  
2411 49         76 sub _dump_qr {
2412 49         505 my ($self,$pat,$mod)=@_;
2413 49         252 my %counts;
2414 49         117 $counts{$_}++ foreach split //,$pat;
2415 51         88 my ($quotes,$best)=('',length($pat)+1);
2416 51   100     250 foreach my $char (qw( / ! % & <> {} " ),'#') { #"
2417 51 50       170 my $bad=0;
2418 51 100       160 $bad+=$counts{$_}||0 for split //,$char;
2419             ($quotes,$best)=($char,$bad) if $bad<$best;
2420 49 50       104 last unless $best;
2421             }
2422             $pat=~s/(?!\\)([$quotes])/\\$1/g
2423 24     24   228 if $best;
  24         58  
  24         149  
  49         77  
2424             {
2425 49         139 use utf8;
  1         8  
2426             #$pat=~s/([^\x00-\x7f])/sprintf '\\x{%x}',ord $1/ge;
2427 49         252 $pat=~s/([^\040-\176])/sprintf "\\x{%x}", ord($1)/ge;
2428             }
2429 49         176 $self->{fh}->print('qr',substr($quotes,0,1),$pat,substr($quotes,-1),$mod);
2430             return
2431             }
2432              
2433             =for uedit32
2434             sub _default_key_sorters{}
2435              
2436             =cut
2437              
2438             my %default_key_sorters= (
2439             numeric => sub { [ sort {$a <=> $b} keys %{$_[0]} ] },
2440             lexical => sub { [ sort keys %{$_[0]} ] },
2441             smart => sub {
2442             [
2443             map { $_->[-1] }
2444             sort {
2445             ( $a->[2] <=> $b->[2] )
2446             ||
2447             ( defined($a->[0])
2448             ? $a->[0] <=> $b->[0] || ($a->[1] cmp $b->[1])
2449             : $a->[1] cmp $b->[1] )
2450             ||
2451             ( $a->[-1] cmp $b->[-1] )
2452             }
2453             map {
2454             my $chars=lc($_);
2455             my $num;
2456             $num=$1 if $chars=~
2457             s/\A(-?(?:0|[1-9]\d{0,8})(?:\.\d{0,15})?)(?!\d)//;
2458             $chars=~s/\W//g;
2459             [ $num, $chars, !defined $num ? 2 :
2460             # length($chars) ? 1 :
2461             0, $_ ]
2462             } keys %{$_[0]}
2463             ]
2464             },
2465             'each'=>sub { undef },
2466             );
2467             $default_key_sorters{alphabetical}=$default_key_sorters{lexical};
2468             $default_key_sorters{intelligent}=$default_key_sorters{smart};
2469             for my $h (\%default_key_sorters) {
2470             my $abr=Text::Abbrev::abbrev(keys %$h);
2471             foreach my $short (keys %$abr) {
2472             $h->{$short}=$h->{$abr->{$short}};
2473             }
2474             }
2475              
2476 1017     1017   2069  
2477             sub _get_keys {
2478 1017         1393 my ($self,$item,$pass,$addr,$class)=@_;
2479 1017 100       2232  
2480             my $sorter;
2481             $class= "" if ! defined $class;
2482 1017   100     3914  
2483 1017 100       2081 $sorter= $self->{style}{sortkeys}{"#$addr"}
2484             || $self->{cache_sorter}{$class};
2485             if ( ! $sorter ) {
2486 238   33     1586 $sorter= $self->{style}{sortkeys}{".$class"}
2487             || ($class && $class->can("DDS_sortkeys") )
2488             || $self->{style}{sortkeys}{"."};
2489 238   66     1014 ;
2490             $self->{cache_sorter}{$class}=
2491 1017         2325 ($sorter ||= $default_key_sorters{smart});
2492 1017 50 33     5737 }
2493             my ($ary,$thaw)=$sorter->( $item, $pass, $addr, $class );
2494 1017         2595 die "$item:$pass:$addr:$class:$ary:$thaw"
2495             if $ary and reftype($ary) ne "ARRAY";
2496             return ($ary,$thaw);
2497             }
2498              
2499 508     508   1254  
2500             sub _dump_hash {
2501             my ($self,$item,$depth,$dumped,$name,$indent,$addr,$class)=@_;
2502              
2503 508         1217 #Carp::confess "$name" unless defined $self->{ref_hkcnt}{$addr};
2504 508 50 33     1880  
2505 0         0 my ($keyary)= $self->_get_keys($item,1,$addr,$class);
2506             if ($keyary and $DEBUG) {
2507             warn "Keys: $keyary : @$keyary"
2508 508         1131 }
2509              
2510 508   100     2464 my $full_indent=$self->{style}{indent}>1;
2511             my $ind=($self->{style}{indent}) &&
2512 508         2113 (!defined($self->{ref_hkcnt}{$addr}) or $self->{ref_hkcnt}{$addr}>1);
2513              
2514 508 100 66     1588 $self->_brace($name,'{',$ind,$indent,$self->{ref_hkcnt}{$addr}) ;
2515              
2516 508         763 my $indkey=($ind && $self->{style}{indentkeys}) ? $self->{ref_hklen}{$addr} : 0;
2517 508         787  
2518 508         844 my $cindent= $indent;
2519 508         1011 my $style= $self->{style};
2520 508         891 my $optspace= $style->{optspace};
2521 508 100       1042 my $sep= $optspace . $self->{style}{hashsep} . $optspace;
2522 149         262 my $pairsep= $self->{style}{pairsep};
2523             if ($indkey) {
2524 508 50       1010 $cindent+= $indkey + length($sep);
2525 508         980 }
2526 508         714 $DEBUG==10 and print "Indent $ind $indkey $cindent\n";
2527 508         1075 my ($kc,$ix)=(0,0);
2528             my $last_n=0;
2529 508 50       1582 my $ind_str=" " x $indent;
2530 1191 100       2883  
2531 1191 100       2232 while (defined(my $k=defined $keyary ? $keyary->[$ix++] : each %$item)) {
2532 696   66     1985 $last_n=0 if ref $item->{$k};
2533 696 100       2596 if ( $kc ) {
2534 696         1210 my $do_ind=$ind && !$last_n ;
2535 696 100 33     1283 $self->{fh}->print($pairsep, $do_ind ? "\n$ind_str" : $optspace);
    50 33        
2536 686         1092 $self->{buf}++;
2537             if ($do_ind) {
2538 0         0 $self->{buf}=0;
2539 0         0 } elsif (!$do_ind && !$optspace && $self->{buf} > 1024 ) {
2540             $self->{fh}->print("\n");
2541             $self->{buf}=0;
2542             }
2543 495         744 } else {
2544             #$self->{fh}->print("\n$ind_str") if !$last_n;
2545 1191 100       2060 $kc=1;
2546 835         1565 }
2547 835 50       2577 if ($indkey) {
2548             my $qk=_quotekey($k);
2549             my $str=$indkey>=length($qk)
2550             ? join "",$qk," " x ($indkey-length($qk)), $sep
2551             : join "",$qk,"\n$ind_str"," " x $indkey, $sep
2552 835         1523 ;
2553 835         2090  
2554             $self->{buf}+=length($str);
2555 356         776 $self->{fh}->print($str);
2556 356         713 } else {
2557 356         975 my $str=_quotekey($k).$sep;
2558             $self->{buf}+=length($str);
2559 1191         3172 $self->{fh}->print($str);
2560             }
2561             my $alias=$self->_dump_sv($item->{$k},$depth+1,$dumped,
2562             $self->_build_name($name,'{',$k),
2563 1191 100 100     3638 $cindent
      66        
2564             );
2565 6         10 if (!$full_indent and !$self->{do_nl} and $self->{buf}<60) {
2566             #warn "$self->{buf}\n";
2567             $last_n++;
2568 1185         1737 } else {
2569             #warn "$self->{buf}\n";
2570 1191 100       4530 $last_n=0;
2571 6         24 }
2572             if ($alias) {
2573             $self->_add_fix('sub call','alias_hv',
2574             $self->_build_name($name,'%'),
2575             _quote($k),
2576             $alias
2577             );
2578 508         1633 }
2579             }
2580 508         1363 $self->_brace($name,'}',$ind,$indent,$self->{ref_hkcnt}{$addr});
2581             return
2582             }
2583 390     390   875  
2584 390         807 sub _dump_array {
2585 390   100     1292 my ($self,$item,$depth,$dumped,$name,$indent)=@_;
2586             my $full_indent=$self->{style}{indent}>1;
2587 390         1247 my $ind=$self->{style}{indent} && @$item>1;
2588 390         628  
2589 390         780 $self->_brace($name,'[',$ind,$indent,scalar @$item);
2590 390         611 my $last_n=0;
  390         1121  
2591 390 100       917 my $ind_str=(" " x $indent);
2592 2         6 my ($optspace,$sep)=@{$self->{style}}{qw(optspace arysep)};
2593 18   33     65 unless ($self->{style}{rle} ) {
2594 18 100       36 foreach my $k (0..$#$item) {
2595 16 50       63 my $do_ind=$ind && (!$last_n || ref $item->[$k]);
2596 16 50 0     32 if ($k) {
    0 0        
2597 16         28 $self->{fh}->print($sep, $do_ind ? "\n$ind_str" : $optspace);
2598             if ($do_ind) {
2599 0         0 $self->{buf}=0;
2600 0         0 } elsif (!$do_ind && !$optspace && $self->{buf} > 1024 ) {
2601             $self->{fh}->print("\n");
2602             $self->{buf}=0;
2603             }
2604             }
2605 18         46  
2606              
2607             my $alias=$self->_dump_sv($item->[$k],$depth+1,$dumped,
2608             $self->_build_name($name,'[',$k),
2609             $indent
2610 18 50 33     61 );
      33        
2611              
2612 0         0 if (!$full_indent and !$self->{do_nl} and $self->{buf}<60) {
2613             #warn "$last_n\n";
2614 18         24 $last_n++;
2615             } else {
2616 18 50       45 $last_n=0;
2617 0         0 }
2618             if ($alias) {
2619             $self->_add_fix('sub call','alias_av',
2620             $self->_build_name($name,'@'),
2621             $k,
2622             $alias
2623             );
2624             }
2625             }
2626             } else {
2627 388         1097 # this is evil and must be changed.
2628 1043         1822 # ... evil ... totally evil... blech
2629 1043         1552 for ( my $k = 0 ; $k <= $#$item ; ) {
2630 1043 100 100     5146 my $v = $item->[$k];
      100        
      100        
2631             my $count = 1;
2632             if (!refaddr($item->[$k]) and !readonly($item->[$k])
2633             and (!$self->{sv}{refaddr(\$item->[$k])} or
2634             $self->{svt}[$self->{sv}{refaddr(\$item->[$k])}]==1)
2635 293   100     3007 )
      66        
      100        
      100        
      100        
      66        
2636             {
2637             COUNT:while (
2638             $k + $count <= $#$item
2639              
2640             and !refaddr($item->[ $k + $count ])
2641              
2642             and !readonly($item->[ $k + $count ])
2643              
2644             and (!$self->{sv}{refaddr(\$item->[$k + $count])} or
2645             $self->{svt}[$self->{sv}{refaddr(\$item->[$k + $count])}]==1)
2646              
2647             and !$v == !$item->[ $k + $count ]
2648              
2649             and defined($v) == defined($item->[ $k + $count ])
2650             )
2651 224 50       555  
2652 0 0       0 {
2653             if (!defined( $item->[ $k + $count ] )) {
2654             last COUNT if defined($v);
2655 224 100       723 } else {
2656             last COUNT if
2657 55         560 $v ne overload::StrVal( $item->[ $k + $count ] )
2658             }
2659             $count++;
2660             }
2661 1043   66     4462 }
2662 1043 100       3872  
    100          
2663             my $do_ind=$ind && (!$last_n || ref $item->[$k]);
2664 1043 100 100     3825 $self->{fh}->print($sep, $do_ind ? "\n$ind_str" : $optspace)
2665 1043 100       2458 if $k;
2666 19         73 $self->{buf}=0 if $do_ind and $k;
2667 19         41 if ($count>1){
2668             $self->{fh}->print("($optspace");
2669 1043         2616 $self->{buf}+=2;
2670             }
2671             my $alias=$self->_dump_sv($item->[$k],$depth+1,$dumped,
2672             $self->_build_name($name,'[',$k),
2673 1043 100 66     3253 $indent
      66        
2674 18         31 );
2675             if (!$full_indent and !$self->{do_nl} and $self->{buf}<60) {
2676 1025         1603 $last_n++;
2677             } else {
2678 1043 100       1963 $last_n=0;
2679 46         108 }
2680             if ($alias) {
2681             $self->_add_fix('sub call','alias_av',
2682             $self->_build_name($name,'@'),
2683             $k,
2684             $alias
2685 1043 100       2115 );
2686 19         46 }
2687 19         41 if ($count>1) {
2688 19         44 my $str=join $optspace,'',')','x',$count;
2689             $self->{buf}+=length($str);
2690 1043         2784 $self->{fh}->print($str);
2691             }
2692             $k += $count;
2693              
2694 390         1225 }
2695             }
2696 390         845 $self->_brace($name,']',$ind,$indent,scalar @$item);
2697             return
2698             }
2699 0     0   0  
2700 0 0       0 sub __vstr {
    0          
2701 0         0 my ($v,@v);
2702 0         0 unless (@_) {
2703 0         0 $v=$];
2704             } elsif (@_==1) {
2705 0         0 $v=shift;
2706             } else {
2707             @v=@_;
2708 0 0       0 }
  0         0  
2709             return join ".", @v ? (@v,(0) x 3)[0..2]
2710             : map { $v * 1000**$_ % 1000 } 0..2
2711             }
2712 40     40   93  
2713 40 50       120 sub _dump_code {
2714 0         0 my ($self,$item,$name,$indent,$class)=@_;
2715             unless ($self->{style}{deparse}) {
2716 40         154 $self->{fh}->print($self->{style}{codestub});
2717             } else { #deparseopts
2718 40 100       239 my $cv=B::svref_2object($item);
2719 1         6  
2720 1         20 if (ref($cv->ROOT)=~/NULL/) {
2721 1         3 my $gv=$cv->GV;
2722             $self->{fh}->print("\\&",$gv->STASH->NAME,"::",$gv->SAFENAME);
2723             return;
2724 39         86 }
  39         1932  
2725              
2726 39         159 my $deparser=Data::Dump::Streamer::Deparser->new(@{$self->{style}{deparseopts}});
2727 39         74  
2728 39         106 my $used= _get_lexicals($item);
2729 78 100       214 my %targ;
2730 39         81 foreach my $targ (keys %$used) {
2731             next if $targ=~/\D/;
2732 39 50       141 my $addr=refaddr($used->{$targ});
2733             $targ{$targ}=$self->{lexicals}{a2n}{$addr}
2734             if $self->{lexicals}{a2n}{$addr};
2735             }
2736 39         140  
2737             # we added this method, its not a normal method. see bottom of file.
2738 39         111 $deparser->dds_usenames(\%targ);
2739 39         60  
2740             my $bless=undef;
2741 39 50       59 my $code;
  39         96  
2742 39         67 DEPARSE:{
  39         36698  
2743 39 50       193 $bless=($class,bless($item,$bless))[0] if defined $bless;
2744 39 50 33     230 eval { $code=$deparser->coderef2text($item) };
    50 33        
2745             bless $item,$bless if defined $bless;
2746             if (!defined $bless and $@ and
2747 0         0 $@ =~ /^\QUsage: ->coderef2text(CODEREF)\E/)
2748 0         0 {
2749             $bless='CODE';
2750 0         0 redo DEPARSE;
2751             } elsif ($@) {
2752 0         0 warnings::warnif "Using CODE stub for $name as ".
2753 0         0 "B::Deparse->coderef2text (v$B::Deparse::VERSION".
2754 0         0 " on v@{[__vstr]}) failed. Message was:\n $@";
2755             $self->{fh}->print($self->{style}{codestub});
2756             return;
2757             }
2758             }
2759              
2760             #$self->{fh}->print("\n#",join " ",keys %$used,"\n");
2761              
2762 39         90 #$code=~s/^\s*(\([^)]+\)|)\s*/sub$1\n/;
2763              
2764 39 50       164 $code=~s/(\%\{)(\s*\{\}\s*)/$1;$2/g;
2765 39 50       119  
2766 39         158 $code="sub".($code=~/^\s*\(/ ? "" : " ").$code;
  161         418  
2767             if ($self->{style}{indent}) {
2768             $code=~s/\n/"\n"." " x $indent/meg;
2769 39 100       123 }
2770 4         27 #warn $name;
2771             if ($name=~s/^\&//) {
2772 39         203 $code=~s/sub(\s)?/sub $name$1/;
2773             }
2774             $self->{fh}->print("$code");
2775 39         93 }
2776             return
2777             }
2778              
2779             sub _dump_format {
2780 4     4   14 # from link from [ysth]: http://groups.google.com/groups?selm=laUs8gzkgOlT092yn%40efn.org
2781             # translate arg (or reference to it) into a B::* object
2782             my ($self,$item,$name,$indent)=@_;
2783 4 50       17  
2784 4         21  
2785             if ($self->{style}{deparse}) {
2786 4 50       19 my $Bobj = B::svref_2object($item);
2787 4 50       25 # if passed a glob or globref, get the format
2788 4         10 $Bobj = B::GV::FORM($Bobj) if ref $Bobj eq 'B::GV';
2789 4         9 if (ref $Bobj eq 'B::FM') {
2790 4         68 my $format;
2791 4         4332 eval {
2792             my $deparser = Data::Dump::Streamer::Deparser->new();
2793 4 50       21 $format=$deparser->indent($deparser->deparse_format($Bobj));
2794 0         0 };
  0         0  
2795 0         0 if ($@) {
  0         0  
2796             warnings::warnif "B::Deparse (v$B::Deparse::VERSION on v@{[__vstr]}) failed FORMAT ref deparse.\n";
2797 4 50       26 $format="B::Deparse (v$B::Deparse::VERSION on v@{[__vstr]}) failed FORMAT ref deparse.\n.\n";
2798 4         15 }
2799 4         51 my $ind=$self->{style}{indent} ? ' ' x $indent : '';
2800             $format="format F =\n$format";
2801 4         12 $format=~s/^/${ind}# /gm;
2802 4   0     67  
  0         0  
2803             my $end='_EOF_FORMAT_';
2804             $end=~s/T(\d*)_/sprintf "T%02d_",($1||0)+1/e
2805 4         67 while $format=~/$end/;
2806              
2807 4         40 $self->{fh}->print("do{ local *F; my \$F=<<'$end'; \$F=~s/^\\s+# //mg; eval \$F; die \$F.\$@ if \$@; *F{FORMAT};\n$format\n$end\n$ind}");
2808             return
2809             }
2810 0         0 }
2811              
2812             $self->{fh}->print($self->{style}{formatstub});
2813              
2814              
2815             }
2816 9     9   24  
2817             sub _dump_symbol {
2818 9         17 my ($self,$item,$name,$glob,$deref,$depth)=@_;
2819              
2820 9 100       42 my $ret="Symbol::gensym";
2821 9 100       36 $ret="do{ require Symbol; $ret }"
2822             unless $self->{reqs}{Symbol}++;
2823 9         37 $ret="*{ $ret }"
2824 9 50 33     57 if $deref;
2825 9         32 $self->{fh}->print( $ret );
2826             if ($self->{style}{dumpglob} and !$self->{sv_glob_du}{$glob}++) {
2827             $self->_add_fix('glob',$_[1],$glob,$depth+1,$name);
2828             }
2829             }
2830 1998     1998   4458  
2831             sub _dump_rv {
2832 1998         3226 my ($self,$item,$depth,$dumped,$name,$indent,$add_do)=@_;
2833              
2834             my ($addr,$idx,$type,$class,$is_frozen_replacement,$overloaded,
2835 1998 50       2805 $raddr);
  2003         5241  
2836 2003         3948 GETITEM: {
2837 2003         4333 $addr=refaddr($item) or Carp::confess "$name : $item";
2838 2003         3869 $idx=$self->{ref}{$addr};
2839 2003 100 100     4903 $type=reftype($item);
      66        
2840             $class=blessed($item);
2841 2003 50       3655 $class=undef if $class and $class eq 'Regexp' and is_regexp $item;
2842              
2843             $DEBUG and
2844 2003         3178 printf "_dump_rv %d %s %#x\n",$depth,$name,$addr;
2845 2003 100       4241  
2846 5         10 my $ignore=0;
2847 5 50       18 if ($self->{ref_fz}{$addr}) {
    50          
2848 0         0 $item= $self->{ref_fz}{$addr};
2849             if ( ! $item ) {
2850 5         6 $ignore=1;
2851 5         9 } elsif (ref $item) {
  5         7  
2852 5         10 $is_frozen_replacement=1;
2853 5         10 $dumped= \do{my $d};
2854             $raddr=$addr;
2855 0         0 redo GETITEM;
2856 0         0 } else {
2857             $self->{buf}+=length($item);
2858 0         0 $self->{fh}->print($item);
2859             return
2860 1998 100 66     12875 }
      33        
      100        
      66        
2861             }
2862             if ($ignore or $self->{style}{ignore}{"#".($raddr||$addr)} or
2863 1         6 (defined $class and $self->{style}{ignore}{".$class"} )
2864 1         5 ){
2865 1         6 my $str= _quote("Ignored Obj [".overload::StrVal($item)."]");
2866             $self->{buf} += length($str);
2867 1         3 $self->{fh}->print($str);
2868             return
2869             }
2870             }
2871 1997 50       3881  
2872              
2873             unless ($idx) {
2874 0         0 #Carp::confess "Unhandled address $addr $name\n";
2875             # this should only happen for localized globs.
2876 1997         3338 ($idx)=$self->_reg_ref($item,$depth,$name,refcount($item));
2877 1997 50       3504 }
2878 1997         3595 my $optspace=$self->{style}{optspace};
2879 1997         2920 if ($idx) {
2880 1997 100 100     8563 my $pre_dumped=$self->{refdu}[$idx];
    100 100        
2881             my $str="";
2882 182 50       418 if ($pre_dumped and $$pre_dumped) {
2883 182 100       638 # its been dumped totally
2884 58 100       175 $DEBUG and print " predumped $self->{refn}[$idx]\n";
2885 4         23 if ($self->{refn}[$idx]=~/^[\@\%\&]/) {
2886 4         16 if (SvREADONLY_ref($item)) {
2887             my @hidden_keys=sort(hidden_keys(%$item));
2888             $self->_add_fix('lock',$idx,\@hidden_keys);
2889 58 100       290 }
    100          
2890             $str=join "",($class ? "bless($optspace" : ''),
2891             '\\'.$self->{refn}[$idx],
2892 124         249 ($class ? ",$optspace"._quote($class)."$optspace)" : '');
2893             } else {
2894 182         361 $str=$self->{refn}[$idx];
2895 182         704 }
2896             $self->{buf}+=length($str);
2897 182         434 $self->{fh}->print($str);
2898 301 50       654 return
2899             } elsif ($pre_dumped or $self->{refd}[$idx] < $depth) {
2900             $DEBUG and print " inprocess or depth violation: $self->{refd}[$idx] < $depth\n";
2901             # we are in the process of dumping it
2902 301 100 100     1230 # output a place holder and add a fix statement
2903             # XXX is this sigil test correct? why not $?
2904 38 100       169 if ($self->{refn}[$idx]=~/^[\@\%\&]/ and (!$self->{style}{declare})) {
    100          
2905             $str=join"",( $class ? "bless($optspace" : '' ),
2906             '\\'.$self->{refn}[$idx],
2907 263 100       584 ( $class ? ",$optspace"._quote($class)."$optspace)" : '' );
2908             } else {
2909 258 100       1143 if ($self->{style}{purity}) {
    50          
    100          
2910             $str=join"",$add_do ? join($optspace,qw(do { my $v = ),'') : '',
2911             !$self->{style}{verbose} ? "'V'" : _quote("V: ",$self->{refn}[$idx]),
2912             $add_do ? $optspace."}" : '';
2913 258         799  
2914             #Carp::cluck "$name $self->{refd}[$idx] < $depth" if $name=~/\*/;
2915 5         10 $self->_add_fix('ref',$name,$idx,$class);
2916             } else {
2917             $str=$self->{refn}[$idx];
2918 301         624 }
2919 301         1130 }
2920             $self->{buf}+=length($str);
2921 301         737 $self->{fh}->print($str);
2922 1514   33     5251 return
2923             }
2924             $self->{refdu}[$idx]||=$dumped;
2925 0         0 #$name=$self->{refn}[$idx]; # override inherited names. ??? maybe not needed
2926             } else {
2927 1514         2353 Carp::confess "Unhandled object '$item'\n";
2928 1514 100 100     3430 }
2929 26         800 my $isoverloaded=0;
2930 26         46 if (defined $class and overload::Overloaded($item)) {
2931 26         53 disable_overloading( $item );
2932             $overloaded= $class;
2933 1514   66     9965 $isoverloaded= 1;
2934 1514         2588 }
2935 1514 100       2907 my $thaw= $self->{ref_thaw}{$raddr||$addr};
2936 4 50       15 my ($inline,$thawtype);
2937 0         0 if ( $thaw ) {
2938             if ($thaw =~ /[^\w:>()-]/) {
2939 4         13 $thawtype= "code";
2940 4 100       15 } else{
2941             $inline= $thaw=~s/^->//;
2942 4 50 66     26 $thawtype= $thaw=~s/\(\)$// ? "sub" : "method";
2943 0         0 }
2944 0         0 if ($inline && $thawtype eq 'sub') {
2945             $self->{buf}+=length($thaw)+1;
2946             $self->{fh}->print($thaw."(${optspace}");
2947 1514         2353 }
2948 1514   100     4115 }
2949 1514         2255 $self->{do_nl}=1;
2950 1514 100       3198 my $add_lock=($type eq 'HASH') && SvREADONLY_ref($item);
2951 1514 100       2959 my $fix_lock=0;
2952             my @hidden_keys=$add_lock ? sort(hidden_keys(%$item)) : ();
2953 38 100       133 if ($add_lock) {
2954 8         14 #warn "$name\n";
2955 8         13 if ($name!~/^\$/) {
2956             $fix_lock=1;
2957 30 100       177 $add_lock=0;
2958             } else {
2959             $self->{fh}->print("lock_ref_keys",
2960             @hidden_keys ? '_plus' : '',
2961             "(${optspace}"
2962             );
2963             }
2964             }
2965 1514   100     3528  
2966 1514 100 100     3346  
2967 84         448 my $add_bless=defined($class) && ($name!~/^[\@\%\&]/);
2968             if ($add_bless && !$overloaded) {
2969             $self->{fh}->print(substr($self->{style}{bless},0,-1),$optspace);
2970 1514 50       2833 }
2971 1514 100 100     7143  
    100 100        
    100 33        
    100 33        
    100          
    100          
    50          
2972 521 100       1356 $DEBUG and print " $type : Start typecheck\n";
2973 521 100       1096 if ($type eq 'SCALAR' or $type eq 'REF' or $type eq 'GLOB') {
2974 521 100       1261 my ($pat,$mod)=$type eq 'SCALAR' ? regex($item) : ();
    50          
2975 8         28 my $glob=$type eq 'GLOB' ? globname $$item : '';
2976             if ($glob=~/^\*Symbol::GEN/) {
2977             $self->_dump_symbol($_[1],$name,$glob,0,$depth);
2978 0         0 } elsif (defined $pat) {
2979             # its a regex
2980 513         1319 $self->_dump_qr($pat,$mod);
2981             } else {
2982             my $ret=$self->_dump_sv($$item,$depth+1,$dumped,
2983             $self->_build_name($name,'$'),
2984 513 100       1431 $indent,'is_ref'
2985             );
2986             $self->{refdu}[$idx]=$ret if $ret;
2987 390         1239 }
2988             } elsif ($type eq 'ARRAY') {
2989 508         1521 $self->_dump_array($item,$depth,$dumped,$name,$indent);
2990             } elsif ($type eq 'HASH') {
2991 40         131 $self->_dump_hash($item,$depth,$dumped,$name,$indent,$addr,$class);
2992             } elsif ($type eq 'CODE') {
2993             $self->_dump_code($item,$name,$indent,$class);
2994 4         17 } elsif ($type eq 'FORMAT') {
2995             #$self->_dump_code($item,$name,$indent,$class); #muwhahahah
2996 2         11 $self->_dump_format($item,$name,$indent);
2997             } elsif ($type eq 'IO') {
2998 49         200 $self->{fh}->print("*{Symbol::gensym()}{IO}");
2999 49         177 } elsif ($type eq 'ORANGE' || $type eq 'Regexp' || $type eq 'REGEXP') {
3000             my ($pat,$mod)=regex($item);
3001 0         0 $self->_dump_qr($pat,$mod);
3002             } else {
3003 1514 100       3022 Carp::confess "_dump_rv() can't handle '$type' objects yet\n :-(\n";
3004 110 100       250 }
3005 84         324 if ($add_bless) {
3006             unless ( defined $overloaded ) {
3007 26         59 $self->{fh}->print(",${optspace}",_quote($class),$optspace,substr($self->{style}{bless},-1))
3008             } else {
3009 110 100       317 $self->_add_fix('bless',$idx,$overloaded);
3010 26         60 }
3011             if ($isoverloaded) {
3012             restore_overloading( $item, $overloaded );
3013 1514 100 100     3324 }
3014 4         26 }
3015             if ($fix_lock && !defined($class)) {
3016 1514 100       2714 $self->_add_fix('lock',$idx,\@hidden_keys);
3017 30 100       64 }
3018 26         73 if ($add_lock) {
  46         84  
3019             if (@hidden_keys) {
3020 30         98 $self->{fh}->print(",${optspace}",join(",${optspace}",map {_quote($_)} @hidden_keys));
3021             }
3022 1514 100       2725 $self->{fh}->print("${optspace})");
3023 4 100       10 }
3024 1 50       7 if ( $thaw ) {
    50          
3025 0         0 if ($inline) {
3026             if ($thawtype eq 'sub') {
3027 1         5 $self->{fh}->print("${optspace})");
3028             } elsif ($thawtype eq 'method') {
3029             $self->{fh}->print("->$thaw()");
3030             }
3031 3 100       14 #$$dumped=1;
3032             } else {
3033             $self->_add_fix('thaw', $idx, $thaw.($thawtype eq 'sub' ? "()" :"" ));
3034 1514 50 66     5779 }
3035 0 0       0 }
3036 0         0 if ( my $postop=$self->{ref_postop}{$raddr||$addr} ) {
3037             if (ref $postop) {
3038 0         0 $postop->($_[1]);
3039             } else {
3040             $_[1]->$postop();
3041 1514         2386 }
3042             }
3043             $self->{do_nl}=1;
3044 1514         3152  
3045             return
3046             }
3047              
3048             =item Names
3049              
3050             =item Names LIST
3051              
3052             =item Names ARRAYREF
3053              
3054             Takes a list of strings or a reference to an array of strings to use for
3055             var names for the objects dumped. The names may be prefixed by a *
3056             indicating the variable is to be dumped as its dereferenced type if it is
3057             an array, hash or code ref. Otherwise the star is ignored. Other sigils
3058             may be prefixed but they will be silently converted to *'s.
3059              
3060             If no names are provided then names are generated automatically based on
3061             the type of object being dumped, with abbreviations applied to compound
3062             class names.
3063              
3064             If called with arguments then returns the object itself, otherwise in list
3065             context returns the list of names in use, or in scalar context a reference
3066             or undef. In void context with no arguments the names are cleared.
3067              
3068             B
3069             Must be called before C is called.
3070              
3071             If you wish to have no names, use L.
3072              
3073             =cut
3074 65     65 1 8497  
3075 65 100       213 sub Names {
    100          
3076 60 50 66     290 my $self = shift->_safe_self;
3077             if (@_) {
3078             my $v=(@_==1 and reftype $_[0] eq 'ARRAY') ? shift @_ : \@_;
3079 133         370 $self->{unames} = [
3080 133         239 map {
3081 133 50 33     717 ( my $s = $_ ) =~ s/^[\@\%\&-]/*/;
3082             $s=~s/^\$//;
3083 133         420 Carp::confess "Bad name '$_'"
3084 60         152 if $s && $s!~/^\*?\w+$/;
  133         316  
3085 60         367 $s
3086             } grep {defined} @$v ];
3087 3         13 return $self;
3088             } elsif (! defined wantarray ) {
3089             $self->{unames}=[];
3090             }
3091             #elsif ( eval { require PadWalker; 1 } ) {
3092             # print DDumper(PadWalker::peek_my(1));
3093             # return $self;
3094 1 50       10 #}
3095 5 100       27  
3096             return wantarray ? @{$self->{unames}||[]} : $self->{unames}
3097             }
3098              
3099             =item Terse
3100              
3101             =item Terse BOOL
3102              
3103             When true, no variable names will be created. Data will be dumped as
3104             anonymous references or values.
3105              
3106             Dump([])->Out; # $ARRAY1 = []
3107             Dump([])->Terse(1)->Out; # []
3108              
3109             =cut
3110 0     0 1 0  
3111 0 0       0 sub Terse {
3112 0         0 my $self = shift->_safe_self;
3113 0         0 if( @_ ) {
3114             $self->{style}{terse} = shift;
3115             return $self;
3116 0         0 }
3117             else {
3118             return $self->{style}{terse};
3119             }
3120             }
3121              
3122              
3123             =for UEDIT
3124             sub Purity {}
3125              
3126             =item Purity
3127              
3128             =item Purity BOOL
3129              
3130             This option can be used to set the level of purity in the output. It
3131             defaults to TRUE, which results in the module doing its best to ensure
3132             that the resulting dump when eval()ed is precisely the same as the input.
3133             However, at times such as debugging this can be tedious, resulting in
3134             extremely long dumps with many "fix" statements involved. By setting
3135             Purity to FALSE the resulting output won't necessarily be legal Perl, but
3136             it will be more legible. In this mode the output is broadly similar to
3137             that of the default setting of Data::Dumper (Purity(0)). When set to TRUE
3138             the behaviour is likewise similar to Data::Dumper in Purity(1) but more
3139             accurate.
3140              
3141             When Purity() is set to FALSE aliases will be output with a function call
3142             wrapper of 'alias_to' whose argument will be the value the item is an
3143             alias to. This wrapper does nothing, and is only there as a visual cue.
3144             Likewise, 'make_ro' will be output when the value was readonly, and again
3145             the effect is cosmetic only.
3146              
3147             =item To
3148              
3149             =item To STREAMER
3150              
3151             Specifies the object to print to. Data::Dump::Streamer can stream its
3152             output to any object supporting the print method. This is primarily meant
3153             for streaming to a filehandle, however any object that supports the method
3154             will do.
3155              
3156             If a filehandle is specified then it is used until it is explicitly
3157             changed, or the object is destroyed.
3158              
3159             =cut
3160 0     0 1 0  
3161 0 0       0 sub To {
3162 0         0 my $self = shift->_safe_self;
3163 0         0 if (@_) {
3164             $self->{fh} = shift;
3165 0         0 return $self;
3166             }
3167             return $self->{fh};
3168             }
3169              
3170             =for UEDIT
3171             sub Declare {}
3172              
3173             =item Declare
3174              
3175             =item Declare BOOL
3176              
3177             If Declare is True then each object is dumped with 'my' declarations
3178             included, and all rules that follow are obeyed. (Ie, not referencing an
3179             undeclared variable). If Declare is False then all objects are expected to
3180             be previously defined and references to top level objects can be made at
3181             any time.
3182              
3183             Defaults to False.
3184              
3185             =cut
3186 8     8 1 422  
3187 8 50       25 sub Indent {
3188 8         15 my $self=shift->_safe_self();
3189             if (@_) {
3190 8 100 66     64 my $val=shift;
    100 66        
3191 3         11  
3192 3         9 if ( $val == 0 && length $self->{style}{optspace} ) {
3193             $self->{style}{last_optspace}= $self->{style}{optspace};
3194             $self->{style}{optspace}= "";
3195 2         6 } elsif( !$self->{style}{indent} && ! length $self->{style}{optspace} )
3196             {
3197 8         15 $self->{style}{optspace}= $self->{style}{last_optspace};
3198 8         146 }
3199             $self->{style}{indent}= $val;
3200             return $self
3201 0         0 } else {
3202             return $self->{style}{indent}
3203             }
3204             }
3205              
3206             =item Indent
3207              
3208             =item Indent INT
3209              
3210             If Indent is True then data is output in an indented and fairly neat
3211             fashion. If the value is 2 then hash key/value pairs and array values each
3212             on their own line. If the value is 1 then a "smart" indenting mode is
3213             activated where multiple key/value or values may be printed to the same
3214             line. The heuristics for this mode are still experimental so it may
3215             occasional not indent very nicely.
3216              
3217             Default is Indent(2)
3218              
3219             If indent is False then no indentation is done, and all optional whitespace.
3220             is omitted. See for more details.
3221              
3222             Defaults to True.
3223              
3224             Newlines are appended to each statement regardless of this value.
3225              
3226             =for UEDIT
3227             sub IndentKeys {}
3228              
3229             =item Indentkeys
3230              
3231             =item Indentkeys BOOL
3232              
3233             If Indent() and Indentkeys are True then hashes with more than one key
3234             value pair are dumped such that the keys and values line up. Note however
3235             this means each key has to be quoted twice. Not advised for very large
3236             data structures. Additional logic may enhance this feature soon.
3237              
3238             Defaults to True.
3239              
3240             B
3241             Must be set before C is called.
3242              
3243             =for UEDIT
3244             sub OptSpace {}
3245              
3246             =item OptSpace
3247              
3248             =item OptSpace STR
3249              
3250             Normally DDS emits a lot of whitespace in between tokens that it
3251             emits. Using this method you can control how much whitespace it
3252             will emit, or even if some other string should be used.
3253              
3254             If Indent is set to 0 then this value is automatically set to
3255             the empty string. When Indent is set back to a non zero value
3256             the old value will be restored if it has not been changed from
3257             the empty string in the intervening time.
3258              
3259             =for UEDIT
3260             sub Keyorder {}
3261              
3262             =item KeyOrder TYPE_OR_OBJ
3263              
3264             =item KeyOrder TYPE_OR_OBJ, VALUE
3265              
3266             Sets or returns the key order to for use for a given type or object.
3267              
3268             TYPE_OR_OBJ may be a string representing a class, or "" for representing
3269             unblessed objects, or it maybe a reference to a hash.
3270              
3271             VALUE may be a string representing one of built in sort mechanisms, or
3272             it may be a reference to a subroutine, or a method name if TYPE_OR_OBJ
3273             is not an object.
3274              
3275             The built in sort mechanisms are 'aphabetical'/'lexical', 'numeric',
3276             'smart'/'intelligent' and 'each'.
3277              
3278             If VALUE is omitted returns the current value for the given type.
3279              
3280             If TYPE_OR_OBJ is omitted or FALSE it defaults to "" which represents
3281             unblessed hashes.
3282              
3283             See L<"Controlling Hash Traversal and Display Order"> for more details.
3284              
3285             =item SortKeys
3286              
3287             =item SortKeys VALUE
3288              
3289             This is a wrapper for KeyOrder. It allows only the generic hash
3290             sort order to be specified a little more elegantly than via KeyOrder().
3291             It is syntactically equivalent to
3292              
3293             $self->KeyOrder( "", @_ );
3294              
3295             =for UEDIT
3296             sub Verbose {}
3297              
3298             =item Verbose
3299              
3300             =item Verbose BOOL
3301              
3302             If Verbose is True then when references that cannot be resolved in a
3303             single statement are encountered the reference is substituted for a
3304             descriptive tag saying what type of forward reference it is, and to what
3305             is being referenced. The type is provided through a prefix, "R:" for
3306             reference, and "A:" for alias, "V:" for a value and then the name of the
3307             var in a string. Automatically generated var names are also reduced to
3308             the shortest possible unique abbreviation, with some tricks thrown in
3309             for Long::Class::Names::Like::This (which would abbreviate most likely
3310             to LCNLT1)
3311              
3312             If Verbose if False then a simple placeholder saying 'A' or 'R' is
3313             provided. (In most situations perl requires a placeholder, and as such
3314             one is always provided, even if technically it could be omitted.)
3315              
3316             This setting does not change the followup statements that fix up the
3317             structure, and does not result in a loss of accuracy, it just makes it a
3318             little harder to read. OTOH, it means dumps can be quite a bit smaller
3319             and less noisy.
3320              
3321             Defaults to True.
3322              
3323             B
3324             Must be set before C is called.
3325              
3326             =for UEDIT
3327             sub DumpGlob {}
3328              
3329             =item DumpGlob
3330              
3331             =item DumpGlob BOOL
3332              
3333             If True then globs will be followed and fully defined, otherwise the globs
3334             will still be referenced but their current value will not be set.
3335              
3336             Defaults to True
3337              
3338             B
3339             Must be set before C is called.
3340              
3341             =for UEDIT
3342             sub Deparse {}
3343              
3344             =item Deparse
3345              
3346             =item Deparse BOOL
3347              
3348             If True then CODE refs will be deparsed use L and
3349             included in the dump. If it is False the a stub subroutine reference will
3350             be output as per the setting of C.
3351              
3352             Caveat Emptor, dumping subroutine references is hardly a secure act, and
3353             it is provided here only for convenience.
3354              
3355             Note using this routine is at your own risk as of DDS 1.11, how it
3356             interacts with the newer advanced closure dumping process is undefined.
3357              
3358             =for UEDIT
3359             sub EclipseName {}
3360              
3361             =item EclipseName
3362              
3363             =item EclipseName SPRINTF_FORMAT
3364              
3365             When necessary DDS will rename vars output during deparsing with this
3366             value. It is a sprintf format string that should contain only and both of
3367             the "%s" and a "%d" formats in any order along with whatever other literal
3368             text you want in the name. No checks are performed on the validity of this
3369             value so be careful. It defaults to
3370              
3371             "%s_eclipse_%d"
3372              
3373             where the "%s" represents the name of the var being eclipsed, and the "%d"
3374             a counter to ensure all such mappings are unique.
3375              
3376             =for UEDIT
3377             sub DeparseOpts {}
3378              
3379             =item DeparseOpts
3380              
3381             =item DeparseOpts LIST
3382              
3383             =item DeparseOpts ARRAY
3384              
3385             If Deparse is True then these options will be passed to B::Deparse->new()
3386             when dumping a CODE ref. If passed a list of scalars the list is used as
3387             the arguments. If passed an array reference then this array is assumed to
3388             contain a list of arguments. If no arguments are provided returns a an
3389             array ref of arguments in scalar context, and a list of arguments in list
3390             context.
3391              
3392             Note using this routine is at your own risk as of DDS 1.11, how it
3393             interacts with the newer advanced closure dumping process is undefined.
3394              
3395             =for UEDIT
3396             sub CodeStub {}
3397              
3398             =item CodeStub
3399              
3400             =item CodeStub STRING
3401              
3402             If Deparse is False then this string will be used in place of CODE
3403             references. Its the users responsibility to make sure its compilable and
3404             blessable.
3405              
3406             Defaults to 'sub { Carp::confess "Dumped code stub!" }'
3407              
3408             =for UEDIT
3409             sub FormatStub {}
3410              
3411             =item FormatStub
3412              
3413             =item FormatStub STRING
3414              
3415             If Deparse is False then this string will be used in place of FORMAT
3416             references. Its the users responsibility to make sure its compilable and
3417             blessable.
3418              
3419             Defaults to 'do{ local *F; eval "format F =\nFormat Stub\n.\n"; *F{FORMAT} }'
3420              
3421             =for UEDIT
3422             sub DeparseGlob {}
3423              
3424             =item DeparseGlob
3425              
3426             =item DeparseGlob BOOL
3427              
3428             If Deparse is TRUE then this style attribute will determine if subroutines
3429             and FORMAT's contained in globs that are dumped will be deparsed or not.
3430              
3431             Defaults to True.
3432              
3433             =for UEDIT
3434             sub DualVars {}
3435             sub Dualvars {}
3436              
3437             =item Dualvars
3438              
3439             =item Dualvars BOOL
3440              
3441             =item Dualvars
3442              
3443             =item Dualvars BOOL
3444              
3445             If TRUE then dualvar checking will occur and the required statements
3446             emitted to recreate dualvars when they are encountered, otherwise items
3447             will be dumped in their stringified form always. It defaults to TRUE.
3448              
3449             =for UEDIT
3450             sub Rle {}
3451             sub RLE {}
3452              
3453             =item Rle
3454              
3455             =item Rle BOOL
3456              
3457             =item RLE
3458              
3459             =item RLE BOOL
3460              
3461             If True then arrays will be run length encoded using the C operator.
3462             What this means is that if an array contains repeated elements then
3463             instead of outputting each and every one a list multiplier will be output.
3464             This means that considerably less space is taken to dump redundant data.
3465              
3466             =item Freezer
3467              
3468             =item Freezer ACTION
3469              
3470             =item Freezer CLASS, ACTION
3471              
3472             This method can be used to override the DDS_freeze hook for a
3473             specific class. If CLASS is omitted then the ACTION applies to
3474             all blessed object.
3475              
3476             If ACTION is false it indicates that the given CLASS should not
3477             have any serilization hooks called.
3478              
3479             If ACTION is a string then it is taken to be the method name that
3480             will be executed to freeze the object. CLASS->can(METHOD) must return
3481             true or the setting will be ignored.
3482              
3483             If ACTION is a code ref it is executed with the object as the argument.
3484              
3485             When called with no arguments returns in scalar context the generic
3486             serialization method (defaults to 'DDS_freeze'), in list context
3487             returns the generic serialization method followed by a list of pairs
3488             of Classname=>ACTION.
3489              
3490             If the action executes a sub or method it is expected to return
3491             a list of three values:
3492              
3493             ( $proxy, $thaw, $postdump )=$obj->DDS_Freeze();
3494              
3495             See L for more details.
3496              
3497             B
3498             Must be set before C is called.
3499              
3500             =cut
3501 2     2 1 762  
3502 2 50       7 sub Freezer {
    0          
3503 2         7 my $self= shift;
3504 2         10 if ( @_==1 ) {
3505             $self->{style}{freezer}= shift;
3506 0         0 return $self;
3507 0         0 } elsif ( @_==2 ) {
3508 0         0 my ( $class, $action )= @_;
3509             $self->{style}{freeze_class}{$class}= $action;
3510             return $self;
3511 0         0 }
3512 0         0 return wantarray ? ($self->{style}{freezer},
3513 0 0       0 map { $_ => $self->{style}{freeze_class}{$_} }
3514             keys %{$self->{style}{freeze_class}} )
3515             : $self->{style}{freezer};
3516             }
3517 1     1 0 433  
3518 1         4 sub ResetFreezer {
3519 1         3 my $self=shift;
3520 1         6 $self->{style}{freezer}='DDS_freeze';
3521             $self->{style}{freeze_class}={};
3522             return $self;
3523             }
3524              
3525             =item Ignore
3526              
3527             =item Ignore OBJ_OR_CLASS
3528              
3529             =item Ignore OBJ_OR_CLASS, BOOL
3530              
3531             Allows a given object or class to be ignored, and replaced with
3532             a string containing the name of the item ignored.
3533              
3534             If called with no args returns a list of items ignored (using the refaddr
3535             to represent objects). If called with a single argument returns whether
3536             that argument is ignored. If called with more than one arguments then
3537             expects a list of pairs of object => is_ignored.
3538              
3539             Returns $self when setting.
3540              
3541             B
3542             Must be set before C is called.
3543              
3544             =cut
3545 2     2 1 657  
3546 2 50       10 sub Ignore {
3547 0         0 my $self=shift;
  0         0  
  0         0  
  0         0  
3548             if (@_==0) {
3549 2 50 33     21 return map { s/^.//; $_ } keys %{$self->{style}{ignore}};
3550             }
3551 2         6 Carp::confess("Must have an even number of arguments in Ignore()")
3552 2         4 if @_>1 && @_ %2;
3553 2 50       13 while (@_) {
3554 0         0 my $item=shift;
3555             if ( ref $item ) {
3556 2         5 $item="#".refaddr($item);
3557             } else {
3558 2 50       7 $item=".$item";
3559 0         0 }
3560             if ( ! @_ ) {
3561 2 100       7 return $self->{style}{ignore}{$item};
3562 1         9 }
3563             if ( shift ) {
3564 1         4 $self->{style}{ignore}{$item}= 1;
3565             } else {
3566             delete $self->{style}{ignore}{$item};
3567 2         10 }
3568             }
3569             return $self;
3570             }
3571              
3572             =for UEDIT
3573             sub Compress {}
3574              
3575             =item Compress
3576              
3577             =item Compress SIZE
3578              
3579             Controls compression of string values (not keys). If this value
3580             is nonzero and a string to be dumped is longer than its value then
3581             the L if defined is used to compress
3582             the string. Setting size to -1 will cause all strings to be
3583             processed, setting size to 0 will cause no strings to be processed.
3584              
3585             =for UEDIT
3586             sub Compressor {}
3587              
3588             =item Compressor
3589              
3590             =item Compressor CODE
3591              
3592             This attribute is used to control the compression of strings.
3593             It is expected to be a reference to a subroutine with the following
3594             interface:
3595              
3596             my $prelude_code=$compressor->(); # no arguments.
3597             my $code=$compressor->('string'); # string argument
3598              
3599             The sub will be called with no arguments at the beginning of the
3600             dump to allow any require statements or similar to be added. During
3601             the dump the sub will be called with a single argument when
3602             compression is required. The code returned in this case is expected
3603             to be an EXPR that will evaluate back to the original string.
3604              
3605             By default DDS will use L in conjunction with
3606             L to do compression and encoding, and exposes the
3607             'usqz' subroutine for handling the decoding and decompression.
3608              
3609             The abbreviated name was chosen as when using the default compressor
3610             every string will be represented by a string like
3611              
3612             usqz('....')
3613              
3614             Meaning that eight characters are required without considering the
3615             data itself. Likewise Base64 was chosen because it is a representation
3616             that is high-bit safe, compact and easy to quote. Escaped strings are
3617             much less efficient for storing binary data.
3618              
3619             =cut
3620              
3621             # weird styling here deliberate.
3622             sub
3623 0     0 1 0 DeparseOpts
3624 0 0       0 {
3625 0 0       0 my $self=shift;
3626 0         0 if (@_) {
3627             if (ref $_[0]) {
3628 0         0 $self->{style}{deparseopts}=shift;
3629             } else {
3630 0         0 $self->{style}{deparseopts}=[@_];
3631             }
3632 0         0 return $self;
3633 0 0       0 } else {
3634             return wantarray ? @{$self->{style}{deparseopts}}
3635             : $self->{style}{deparseopts};
3636             }
3637             }
3638 9     9 1 45  
3639 9 50 66     32 sub KeyOrder {
3640             my $self= shift;
3641             Carp::croak("KeyOrder() Must have an even number of arguments if doing a multiple set.")
3642 9         22 if @_>2 and @_ % 2;
3643 9         15  
3644 9         13 while (@_) {
3645 9 100       21 my $obj= shift;
3646 2         7 my $name;
3647             if (ref $obj) {
3648 7 50       17 $name= "#" .refaddr($obj)
3649 7         19 } else {
3650             $name= "" if ! defined $obj;
3651 9 50       21 $name= ".$obj";
3652             }
3653 0   0     0 if ( ! @_ ) {
3654             return $self->{style}{sortkeys_string}{$name}||
3655 9         15 $self->{style}{sortkeys}{$name};
3656 9 50       20 }
3657 0         0 my $val= shift;
3658 0         0 if ( ! defined $val ) {
3659             delete $self->{style}{sortkeys}{$name};
3660 9 100       38 delete $self->{style}{sortkeys_string}{$name};
    100          
    50          
3661 5         12 } else {
3662 5 50 33     45 if ( ! ref $val ) {
      33        
3663             my $subref= $default_key_sorters{$val};
3664             Carp::confess("Unblessed or per object Sortkeys() must be coderefs:'$val'\n")
3665 5   33     13 if (!$subref or $name eq "." )
3666 5 50 0     13 and reftype($subref) ne "CODE";
3667             $subref ||= $obj->can($val);
3668             die "Unknown sortkeys '$val', and "
3669 5         13 . (ref($obj)||$obj)." doesn't know how to do it.\n"
3670 5         11 if !$subref;
3671             $self->{style}{sortkeys_string}{$name}=$val;
3672 2         3 $val= $subref;
3673 2     8   8 } elsif ( reftype($val) eq 'ARRAY' ) {
  8         17  
3674             my $aryref= $val;
3675 0         0 $val= sub{ return $aryref; };
3676             } elsif ( reftype($val) ne 'CODE' ) {
3677 9         35 Carp::confess("Can't use '$val' as KeyOrder() value");
3678             }
3679             $self->{style}{sortkeys}{$name}= $val;
3680 9         40 }
3681             }
3682             return $self;
3683             }
3684 6     6 1 937 *Keyorder=*KeyOrder;
3685 6         20 sub SortKeys {
3686             my $self=shift;
3687             $self->KeyOrder("",@_);
3688             }
3689             *Sortkeys= *SortKeys;
3690             *HashKeys = *Hashkeys = *KeyOrder;
3691              
3692             my %scalar_meth=map{ $_ => lc($_)}
3693             qw(Declare Indent IndentCols IndentKeys
3694             Verbose DumpGlob Deparse DeparseGlob DeparseFormat CodeStub
3695             FormatStub Rle RLE Purity DualVars Dualvars EclipseName
3696             Compress Compressor OptSpace);
3697 23     23   244407  
3698 23         62 sub AUTOLOAD {
3699 23 50       132 (my $meth=$AUTOLOAD)=~s/^((?:\w+::)+)//;
    0          
3700 23 50       84 my $name;
3701 23 100   221 1 2643 if (defined($name=$scalar_meth{$meth})) {
  221 50   2 1 143645  
  221 50   3 0 823  
  57 50   2 1 190  
  57 50   4 1 346  
  164 50   2 1 583  
  2         10  
  2         8  
  2         11  
  2         10  
  0         0  
  3         12  
  3         10  
  3         13  
  3         16  
  0         0  
  2         31  
  2         8  
  2         10  
  2         5  
  0         0  
  4         14  
  4         14  
  4         15  
  4         38  
  0         0  
  2         16  
  2         11  
  2         41  
  2         16  
  0            
3702             $DEBUG and print "AUTLOADING scalar meth $meth ($name)\n";
3703             eval '
3704             sub '.$meth.' {
3705             my $self=shift->_safe_self();
3706             if (@_) {
3707             $self->{style}{'.$name.'}=shift;
3708             return $self
3709             } else {
3710             return $self->{style}{'.$name.'}
3711             }
3712 23 50       156 }
3713 23         828 ';
3714             $@ and die "$meth:$@\n";
3715 0         0 goto &$meth;
3716             } elsif ($meth=~/[^A-Z]/) {
3717             Carp::confess "Unhandled method/subroutine call $AUTOLOAD";
3718             }
3719             }
3720 79     79   128  
3721             sub _get_lexicals {
3722 79 50       167 my $cv=shift;
3723 79         418  
3724 79 50       240 if ($HasPadWalker) {
3725 0         0 my ($names,$targs)=PadWalker::closed_over($cv);
3726             if ($PadWalker::VERSION < 1) {
3727 79         348 $names->{$_}=$names->{$targs->{$_}} for keys %$targs;
3728             } else {
3729 79         246 %$names=(%$names,%$targs);
3730             }
3731             return $names;
3732 0         0 }
3733 0         0  
  0         0  
3734 0         0 my $svo=B::svref_2object($cv);
  0         0  
3735             my @pl_array = eval { $svo->PADLIST->ARRAY };
3736 0         0 my @name_obj = eval { $pl_array[0]->ARRAY };
3737 0         0  
3738 0 0       0 my %named;
3739 0         0 for my $i ( 0..$#name_obj ) {
3740             if ( ref($name_obj[$i])!~/SPECIAL/) {
3741             $named{$i} = $name_obj[$i]->PV;
3742             }
3743 0         0 }
3744              
3745             my %inited;
3746             my %used;
3747 0     0   0 B::Utils::walkoptree_filtered(
3748             $svo->ROOT,
3749 0     0   0 sub { B::Utils::opgrep { name => [ qw[ padsv padav padhv ] ] }, @_ },
3750 0         0 sub {
3751 0 0       0 my ( $op, @items )=@_;
3752             my $targ = $op->targ;
3753             my $name = $named{$targ}
3754 0 0       0 or return;
3755              
3756             $inited{$name}++
3757 0 0       0 if $op->private & 128;
3758 0         0  
3759 0         0 if ( !$inited{$name} ) {
3760 0         0 $used{$name} = $pl_array[1]->ARRAYelt($targ)->object_2svref;
3761             $used{$targ} = $used{$name};
3762             $inited{$name}++;
3763 0         0 }
3764 0         0 }
3765             );
3766             return \%used;
3767             }
3768 24     24   181257  
  24         73  
  24         8851  
3769             package Data::Dump::Streamer::Deparser;
3770             use B::Deparse;
3771             our @ISA=qw(B::Deparse);
3772             my %cache;
3773              
3774             our $VERSION = '2.41';
3775             $VERSION= eval $VERSION;
3776             if ( $VERSION ne $Data::Dump::Streamer::VERSION ) {
3777             die "Incompatible Data::Dump::Streamer::Deparser v$VERSION vs Data::Dump::Streamer v$Data::Dump::Streamer::VERSION";
3778             }
3779 39     39   67  
3780 39         58 sub dds_usenames {
3781 39         129 my $self=shift;
3782             my $names=shift;
3783             $cache{Data::Dump::Streamer::refaddr $self}=$names;
3784             }
3785 45     45   147  
3786 45         65 sub padname {
3787 45 100 66     300 my $self = shift;
3788 39         4032 my $targ = shift;
3789             if ( $cache{Data::Dump::Streamer::refaddr $self} and $cache{Data::Dump::Streamer::refaddr $self}{$targ} ) {
3790 6         972 return $cache{Data::Dump::Streamer::refaddr $self}{$targ}
3791             }
3792             return $self->padname_sv($targ)->PVX;
3793             }
3794 44     44   146  
3795 44         332 sub DESTROY {
3796             my $self=shift;
3797             delete $cache{Data::Dump::Streamer::refaddr $self};
3798             }
3799              
3800             unless (B::AV->can('ARRAYelt')) {
3801             eval <<' EOF_EVAL';
3802             sub B::AV::ARRAYelt {
3803             my ($obj,$idx)=@_;
3804             my @array=$obj->ARRAY;
3805             return $array[$idx];
3806             }
3807             EOF_EVAL
3808             }
3809              
3810             1;
3811             __END__