File Coverage

blib/lib/Tree/DAG_Node.pm
Criterion Covered Total %
statement 355 788 45.0
branch 143 410 34.8
condition 28 128 21.8
subroutine 39 95 41.0
pod 67 67 100.0
total 632 1488 42.4


line stmt bran cond sub pod time code
1             package Tree::DAG_Node;
2              
3 6     6   725172 use strict;
  6         42  
  6         383  
4 6     6   52 use warnings;
  6         10  
  6         375  
5 6     6   28 use warnings qw(FATAL utf8); # Fatalize encoding glitches.
  6         190  
  6         768  
6              
7             our $Debug = 0;
8             our $VERSION = '1.35';
9              
10 6     6   3652 use File::Slurper 'read_lines';
  6         121564  
  6         96150  
11              
12             # -----------------------------------------------
13              
14             sub add_daughter { # alias
15 436     436 1 1105 my($it,@them) = @_; $it->add_daughters(@them);
  436         1014  
16             }
17              
18             # -----------------------------------------------
19              
20             sub add_daughters { # write-only method
21 465     465 1 858 my($mother, @daughters) = @_;
22 465 50       1055 return unless @daughters; # no-op
23             return
24             $mother->_add_daughters_wrapper(
25 469     469   664 sub { push @{$_[0]}, $_[1]; },
  469         1759  
26             @daughters
27 465         2364 );
28             }
29              
30             # -----------------------------------------------
31              
32             sub add_daughter_left { # alias
33 0     0 1 0 my($it,@them) = @_; $it->add_daughters_left(@them);
  0         0  
34             }
35              
36             # -----------------------------------------------
37              
38             sub add_daughters_left { # write-only method
39 0     0 1 0 my($mother, @daughters) = @_;
40 0 0       0 return unless @daughters;
41             return
42             $mother->_add_daughters_wrapper(
43 0     0   0 sub { unshift @{$_[0]}, $_[1]; },
  0         0  
44             @daughters
45 0         0 );
46             }
47              
48             # -----------------------------------------------
49              
50             sub _add_daughters_wrapper {
51 465     465   1033 my($mother, $callback, @daughters) = @_;
52 465 50       1029 return unless @daughters;
53              
54 465         759 my %ancestors;
55 465         1101 @ancestors{ $mother->ancestors } = undef;
56             # This could be made more efficient by not bothering to compile
57             # the ancestor list for $mother if all the nodes to add are
58             # daughterless.
59             # But then you have to CHECK if they're daughterless.
60             # If $mother is [big number] generations down, then it's worth checking.
61              
62 465         1037 foreach my $daughter (@daughters) { # which may be ()
63 469 50       1874 die "daughter must be a node object!" unless UNIVERSAL::can($daughter, 'is_node');
64              
65 469 50       1124 printf "Mother : %s (%s)\n", $mother, ref $mother if $Debug;
66 469 50       995 printf "Daughter: %s (%s)\n", $daughter, ref $daughter if $Debug;
67 469 50 0     1086 printf "Adding %s to %s\n",
      0        
68             ($daughter->name() || $daughter),
69             ($mother->name() || $mother) if $Debug > 1;
70              
71 469 50       1402 die 'Mother (' . $mother -> name . ") can't be its own daughter\n" if $mother eq $daughter;
72              
73             die "$daughter (" . ($daughter->name || 'no_name') .
74             ") is an ancestor of $mother (" . ($mother->name || 'no_name') .
75 469 50 0     1157 "), so can't became its daughter\n" if exists $ancestors{$daughter};
      0        
76              
77 469         863 my $old_mother = $daughter->{'mother'};
78              
79 469 50 66     1091 next if defined($old_mother) && ref($old_mother) && $old_mother eq $mother;
      66        
80             # noop if $daughter is already $mother's daughter
81              
82 469 100 66     1128 $old_mother->remove_daughters($daughter)
83             if defined($old_mother) && ref($old_mother);
84              
85 469         858 &{$callback}($mother->{'daughters'}, $daughter);
  469         1073  
86             }
87 465         1465 $mother->_update_daughter_links; # need only do this at the end
88              
89 465         2810 return;
90             }
91              
92             # -----------------------------------------------
93              
94             sub add_left_sister { # alias
95 0     0 1 0 my($it,@them) = @_; $it->add_left_sisters(@them);
  0         0  
96             }
97              
98             # -----------------------------------------------
99              
100             sub add_left_sisters { # write-only method
101 0     0 1 0 my($this, @new) = @_;
102 0 0       0 return() unless @new;
103              
104 0         0 @new = $this->replace_with(@new, $this);
105 0         0 shift @new; pop @new; # kill the copies of $this
  0         0  
106 0         0 return @new;
107             }
108              
109             # -----------------------------------------------
110              
111             sub add_right_sister { # alias
112 0     0 1 0 my($it,@them) = @_; $it->add_right_sisters(@them);
  0         0  
113             }
114              
115             # -----------------------------------------------
116              
117             sub add_right_sisters { # write-only method
118 0     0 1 0 my($this, @new) = @_;
119 0 0       0 return() unless @new;
120 0         0 @new = $this->replace_with($this, @new);
121 0         0 shift @new; shift @new; # kill the copies of $this
  0         0  
122 0         0 return @new;
123             }
124              
125             # -----------------------------------------------
126              
127             sub address {
128 0     0 1 0 my($it, $address) = @_[0,1];
129 0 0 0     0 if(defined($address) && length($address)) { # given the address, return the node.
130             # invalid addresses return undef
131 0         0 my $root = $it->root;
132 0         0 my @parts = map {$_ + 0}
  0         0  
133             $address =~ m/(\d+)/g; # generous!
134 0 0       0 die "Address \"$address\" is an ill-formed address" unless @parts;
135 0 0       0 die "Address \"$address\" must start with '0'" unless shift(@parts) == 0;
136              
137 0         0 my $current_node = $root;
138 0         0 while(@parts) { # no-op for root
139 0         0 my $ord = shift @parts;
140 0         0 my @daughters = @{$current_node->{'daughters'}};
  0         0  
141              
142 0 0       0 if($#daughters < $ord) { # illegal address
143 0 0       0 print "* $address has an out-of-range index ($ord)!" if $Debug;
144 0         0 return undef;
145             }
146 0         0 $current_node = $daughters[$ord];
147 0 0       0 unless(ref($current_node)) {
148 0 0       0 print "* $address points to or thru a non-node!" if $Debug;
149 0         0 return undef;
150             }
151             }
152 0         0 return $current_node;
153              
154             } else { # given the node, return the address
155 0         0 my @parts = ();
156 0         0 my $current_node = $it;
157 0         0 my $mother;
158              
159 0   0     0 while(defined( $mother = $current_node->{'mother'} ) && ref($mother)) {
160 0         0 unshift @parts, $current_node->my_daughter_index;
161 0         0 $current_node = $mother;
162             }
163 0         0 return join(':', 0, @parts);
164             }
165             }
166              
167             # -----------------------------------------------
168              
169             sub ancestors {
170 931     931 1 1426 my $this = shift;
171 931         1644 my $mama = $this->{'mother'}; # initial condition
172 931 100       2251 return () unless ref($mama); # I must be root!
173              
174             # Could be defined recursively, as:
175             # if(ref($mama = $this->{'mother'})){
176             # return($mama, $mama->ancestors);
177             # } else {
178             # return ();
179             # }
180             # But I didn't think of that until I coded the stuff below, which is
181             # faster.
182              
183 700         1264 my @ancestors = ( $mama ); # start off with my mama
184 700   66     2403 while(defined( $mama = $mama->{'mother'} ) && ref($mama)) {
185             # Walk up the tree
186 332         925 push(@ancestors, $mama);
187             # This turns into an infinite loop if someone gets stupid
188             # and makes this tree cyclic! Don't do it!
189             }
190 700         2355 return @ancestors;
191             }
192              
193             # -----------------------------------------------
194              
195             sub attribute { # alias
196 0     0 1 0 my($it,@them) = @_; $it->attributes(@them);
  0         0  
197             }
198              
199             # -----------------------------------------------
200              
201             sub attributes { # read/write attribute-method
202             # expects a ref, presumably a hashref
203 852     852 1 1602 my $this = shift;
204 852 100       1729 if(@_) {
205 450 50       1033 die "my parameter must be a reference" unless ref($_[0]);
206 450         980 $this->{'attributes'} = $_[0];
207             }
208 852         1850 return $this->{'attributes'};
209             }
210              
211             # -----------------------------------------------
212              
213             sub clear_daughters { # write-only method
214 22     22 1 20 my($mother) = $_[0];
215 22         20 my @daughters = @{$mother->{'daughters'}};
  22         25  
216              
217 22         19 @{$mother->{'daughters'}} = ();
  22         24  
218 22         26 foreach my $one (@daughters) {
219 7 50       15 next unless UNIVERSAL::can($one, 'is_node'); # sanity check
220 7         7 $one->{'mother'} = undef;
221             }
222             # Another, simpler, way to do it:
223             # $mother->remove_daughters($mother->daughters);
224              
225 22         23 return @daughters; # NEW
226             }
227              
228             # -----------------------------------------------
229              
230             sub common { # Return the lowest node common to all these nodes...
231             # Called as $it->common($other) or $it->common(@others)
232 0     0 1 0 my @ones = @_; # all nodes I was given
233 0         0 my($first, @others) = @_;
234              
235 0 0       0 return $first unless @others; # degenerate case
236              
237 0         0 my %ones;
238 0         0 @ones{ @ones } = undef;
239              
240 0         0 foreach my $node (@others) {
241 0 0       0 die "TILT: node \"$node\" is not a node"
242             unless UNIVERSAL::can($node, 'is_node');
243 0         0 my %first_lineage;
244 0         0 @first_lineage{$first, $first->ancestors} = undef;
245 0         0 my $higher = undef; # the common of $first and $node
246 0         0 my @my_lineage = $node->ancestors;
247              
248             Find_Common:
249 0         0 while(@my_lineage) {
250 0 0       0 if(exists $first_lineage{$my_lineage[0]}) {
251 0         0 $higher = $my_lineage[0];
252 0         0 last Find_Common;
253             }
254 0         0 shift @my_lineage;
255             }
256 0 0       0 return undef unless $higher;
257 0         0 $first = $higher;
258             }
259 0         0 return $first;
260             }
261              
262             # -----------------------------------------------
263              
264             sub common_ancestor {
265 0     0 1 0 my @ones = @_; # all nodes I was given
266 0         0 my($first, @others) = @_;
267              
268 0 0       0 return $first->{'mother'} unless @others;
269             # which may be undef if $first is the root!
270              
271 0         0 my %ones;
272 0         0 @ones{ @ones } = undef; # my arguments
273              
274 0         0 my $common = $first->common(@others);
275 0 0       0 if(exists($ones{$common})) { # if the common is one of my nodes...
276 0         0 return $common->{'mother'};
277             # and this might be undef, if $common is root!
278             } else {
279 0         0 return $common;
280             # which might be null if that's all common came up with
281             }
282             }
283              
284             # -----------------------------------------------
285              
286             sub copy
287             {
288 24     24 1 26 my($from, $o) = @_[0,1];
289 24 50       29 $o = {} unless ref $o;
290              
291             # Straight dup, and bless into same class.
292              
293 24         65 my $to = bless { %$from }, ref($from);
294              
295             # Null out linkages.
296              
297 24         42 $to -> _init_mother;
298 24         31 $to -> _init_daughters;
299              
300             # Dup the 'attributes' attribute.
301              
302 24 50       28 if ($$o{'no_attribute_copy'})
303             {
304 24         31 $$to{attributes} = {};
305             }
306             else
307             {
308 0         0 my $attrib_copy = ref($to->{'attributes'});
309              
310 0 0       0 if ($attrib_copy)
311             {
312 0 0       0 if ($attrib_copy eq 'HASH')
    0          
313             {
314             # Dup the hashref.
315              
316 0         0 $$to{'attributes'} = { %{$$to{'attributes'}} };
  0         0  
317             }
318             elsif ($attrib_copy = UNIVERSAL::can($to->{'attributes'}, 'copy') )
319             {
320             # $attrib_copy now points to the copier method.
321              
322 0         0 $$to{'attributes'} = &{$attrib_copy}($from);
  0         0  
323              
324             } # Otherwise I don't know how to copy it; leave as is.
325             }
326             }
327              
328 24         53 $$o{'from_to'}{$from} = $to; # SECRET VOODOO
329              
330             # ...autovivifies an anon hashref for 'from_to' if need be
331             # This is here in case I later want/need a table corresponding
332             # old nodes to new.
333              
334 24         27 return $to;
335             }
336              
337             # -----------------------------------------------
338              
339             sub copy_at_and_under {
340 24     24 1 57 my($from, $o) = @_[0,1];
341 24 50       27 $o = {} unless ref $o;
342 24         21 my @daughters = map($_->copy_at_and_under($o), @{$from->{'daughters'}});
  24         37  
343 24         31 my $to = $from->copy($o);
344 24 100       40 $to->set_daughters(@daughters) if @daughters;
345 24         62 return $to;
346             }
347              
348             # -----------------------------------------------
349              
350             sub copy_tree {
351 0     0 1 0 my($this, $o) = @_[0,1];
352 0         0 my $root = $this->root;
353 0 0       0 $o = {} unless ref $o;
354              
355 0         0 my $new_root = $root->copy_at_and_under($o);
356              
357 0         0 return $new_root;
358             }
359              
360             # -----------------------------------------------
361              
362             sub daughters { # read-only attrib-method: returns a list.
363 25     25 1 442 my $this = shift;
364              
365 25 50       34 if(@_) { # undoc'd and disfavored to use as a write-method
366 0         0 die "Don't set daughters with daughters anymore\n";
367 0 0       0 warn "my parameter must be a listref" unless ref($_[0]);
368 0         0 $this->{'daughters'} = $_[0];
369 0         0 $this->_update_daughter_links;
370             }
371             #return $this->{'daughters'};
372 25 50       20 return @{$this->{'daughters'} || []};
  25         57  
373             }
374              
375             # ------------------------------------------------
376              
377             sub decode_lol
378             {
379 0     0 1 0 my($self, $result) = @_;
380 0         0 my(@worklist) = $result;
381              
382 0         0 my($obj);
383             my($ref_type);
384 0         0 my(@stack);
385              
386             do
387 0         0 {
388 0         0 $obj = shift @worklist;
389 0         0 $ref_type = ref $obj;
390              
391 0 0       0 if ($ref_type eq 'ARRAY')
    0          
    0          
392             {
393 0         0 unshift @worklist, @$obj;
394             }
395             elsif ($ref_type eq 'HASH')
396             {
397 0         0 push @stack, {%$obj};
398             }
399             elsif ($ref_type)
400             {
401 0         0 die "Unsupported object type $ref_type\n";
402             }
403             else
404             {
405 0         0 push @stack, $obj;
406             }
407              
408             } while (@worklist);
409              
410 0         0 return [@stack];
411              
412             } # End of decode_lol.
413              
414             # -----------------------------------------------
415              
416             sub delete_tree {
417 0     0 1 0 my $it = $_[0];
418             $it->root->walk_down({ # has to be callbackback, not callback
419             'callbackback' => sub {
420 0     0   0 %{$_[0]} = ();
  0         0  
421 0         0 bless($_[0], 'DEADNODE'); # cause become dead! cause become dead!
422 0         0 return 1;
423             }
424 0         0 });
425 0         0 return;
426             # Why DEADNODE? Because of the nice error message:
427             # "Can't locate object method "leaves_under" via package "DEADNODE"."
428             # Moreover, DEADNODE doesn't provide is_node, so fails my can() tests.
429             }
430              
431 0     0   0 sub DEADNODE::delete_tree { return; }
432             # in case you kill it AGAIN!!!!! AND AGAIN AND AGAIN!!!!!! OO-HAHAHAHA!
433              
434             # -----------------------------------------------
435              
436             sub depth_under {
437 0     0 1 0 my $node = shift;
438 0         0 my $max_depth = 0;
439             $node->walk_down({
440             '_depth' => 0,
441             'callback' => sub {
442 0     0   0 my $depth = $_[1]->{'_depth'};
443 0 0       0 $max_depth = $depth if $depth > $max_depth;
444 0         0 return 1;
445             },
446 0         0 });
447 0         0 return $max_depth;
448             }
449              
450             # -----------------------------------------------
451              
452             sub descendants {
453             # read-only method: return a list of my descendants
454 0     0 1 0 my $node = shift;
455 0         0 my @list = $node->self_and_descendants;
456 0         0 shift @list; # lose myself.
457 0         0 return @list;
458             }
459              
460             # -----------------------------------------------
461              
462             sub draw_ascii_tree {
463             # Make a "box" for this node and its possible daughters, recursively.
464              
465             # The guts of this routine are horrific AND recursive!
466              
467             # Feel free to send me better code. I worked on this until it
468             # gave me a headache and it worked passably, and then I stopped.
469              
470 46     46 1 746 my $it = $_[0];
471 46 100       53 my $o = ref($_[1]) ? $_[1] : {};
472 46         44 my(@box, @daughter_boxes, $width, @daughters);
473 46         34 @daughters = @{$it->{'daughters'}};
  46         56  
474              
475 46 100       78 $o->{'no_name'} = 0 unless exists $o->{'no_name'};
476 46 100       62 $o->{'h_spacing'} = 1 unless exists $o->{'h_spacing'};
477 46 100       71 $o->{'h_compact'} = 1 unless exists $o->{'h_compact'};
478 46 100       54 $o->{'v_compact'} = 1 unless exists $o->{'v_compact'};
479              
480 46         35 my $printable_name;
481 46 50       68 if($o->{'no_name'}) {
482 0         0 $printable_name = '*';
483             } else {
484 46 50       57 $printable_name = defined $it->name ? $it->name : $it;
485 46         50 $printable_name =~ tr<\cm\cj\t >< >s;
486 46         58 $printable_name = "<$printable_name>";
487             }
488              
489 46 100       48 if(!scalar(@daughters)) { # I am a leaf!
490             # Now add the top parts, and return.
491 16         22 @box = ("|", $printable_name);
492             } else {
493 30         38 @daughter_boxes = map { &draw_ascii_tree($_, $o) } @daughters;
  44         109  
494              
495 30         28 my $max_height = 0;
496 30         35 foreach my $box (@daughter_boxes) {
497 44         43 my $h = @$box;
498 44 100       54 $max_height = $h if $h > $max_height;
499             }
500              
501 30         48 @box = ('') x $max_height; # establish the list
502              
503 30         29 foreach my $one (@daughter_boxes) {
504 44         47 my $length = length($one->[0]);
505 44         33 my $height = @$one;
506              
507             #now make all the same height.
508 44         38 my $deficit = $max_height - $height;
509 44 100       67 if($deficit > 0) {
510 13         31 push @$one, ( scalar( ' ' x $length ) ) x $deficit;
511 13         12 $height = scalar(@$one);
512             }
513              
514              
515             # Now tack 'em onto @box
516             ##########################################################
517             # This used to be a sub of its own. Ho-hum.
518              
519 44         49 my($b1, $b2) = (\@box, $one);
520 44         53 my($h1, $h2) = (scalar(@$b1), scalar(@$b2));
521              
522 44         36 my(@diffs, $to_chop);
523 44 50       53 if($o->{'h_compact'}) { # Try for h-scrunching.
524 44         36 my @diffs;
525 44         41 my $min_diff = length($b1->[0]); # just for starters
526 44         47 foreach my $line (0 .. ($h1 - 1)) {
527 263         249 my $size_l = 0; # length of terminal whitespace
528 263         225 my $size_r = 0; # length of initial whitespace
529 263 100       445 $size_l = length($1) if $b1->[$line] =~ /( +)$/s;
530 263 100       413 $size_r = length($1) if $b2->[$line] =~ /^( +)/s;
531 263         247 my $sum = $size_l + $size_r;
532              
533 263 100       281 $min_diff = $sum if $sum < $min_diff;
534 263         343 push @diffs, [$sum, $size_l, $size_r];
535             }
536 44         44 $to_chop = $min_diff - $o->{'h_spacing'};
537 44 100       81 $to_chop = 0 if $to_chop < 0;
538             }
539              
540 44 100 66     81 if(not( $o->{'h_compact'} and $to_chop )) {
541             # No H-scrunching needed/possible
542 43         47 foreach my $line (0 .. ($h1 - 1)) {
543 250         309 $b1->[ $line ] .= $b2->[ $line ] . (' ' x $o->{'h_spacing'});
544             }
545             } else {
546             # H-scrunching is called for.
547 1         2 foreach my $line (0 .. ($h1 - 1)) {
548 13         14 my $r = $b2->[$line]; # will be the new line
549 13         11 my $remaining = $to_chop;
550 13 50       14 if($remaining) {
551 13         35 my($l_chop, $r_chop) = @{$diffs[$line]}[1,2];
  13         18  
552              
553 13 50       14 if($l_chop) {
554 0 0       0 if($l_chop > $remaining) {
    0          
555 0         0 $l_chop = $remaining;
556 0         0 $remaining = 0;
557             } elsif($l_chop == $remaining) {
558 0         0 $remaining = 0;
559             } else { # remaining > l_chop
560 0         0 $remaining -= $l_chop;
561             }
562             }
563 13 50       15 if($r_chop) {
564 0 0       0 if($r_chop > $remaining) {
    0          
565 0         0 $r_chop = $remaining;
566 0         0 $remaining = 0;
567             } elsif($r_chop == $remaining) {
568 0         0 $remaining = 0;
569             } else { # remaining > r_chop
570 0         0 $remaining -= $r_chop; # should never happen!
571             }
572             }
573              
574 13 50       14 substr($b1->[$line], -$l_chop) = '' if $l_chop;
575 13 50       14 substr($r, 0, $r_chop) = '' if $r_chop;
576             } # else no-op
577 13         17 $b1->[ $line ] .= $r . (' ' x $o->{'h_spacing'});
578             }
579             # End of H-scrunching ickyness
580             }
581             # End of ye big tack-on
582              
583             }
584             # End of the foreach daughter_box loop
585              
586             # remove any fencepost h_spacing
587 30 50       39 if($o->{'h_spacing'}) {
588 30         29 foreach my $line (@box) {
589 127 50       177 substr($line, -$o->{'h_spacing'}) = '' if length($line);
590             }
591             }
592              
593             # end of catenation
594 30 50       40 die "SPORK ERROR 958203: Freak!!!!!" unless @box;
595              
596             # Now tweak the pipes
597 30         32 my $new_pipes = $box[0];
598 30         31 my $pipe_count = $new_pipes =~ tr<|><+>;
599 30 100       32 if($pipe_count < 2) {
600 26         36 $new_pipes = "|";
601             } else {
602 4         4 my($init_space, $end_space);
603              
604             # Thanks to Gilles Lamiral for pointing out the need to set to '',
605             # to avoid -w warnings about undeffiness.
606              
607 4 50       12 if( $new_pipes =~ s<^( +)><>s ) {
608 4         6 $init_space = $1;
609             } else {
610 0         0 $init_space = '';
611             }
612              
613 4 50       13 if( $new_pipes =~ s<( +)$><>s ) {
614 4         5 $end_space = $1
615             } else {
616 0         0 $end_space = '';
617             }
618              
619 4         6 $new_pipes =~ tr< ><->;
620 4         5 substr($new_pipes,0,1) = "/";
621 4         4 substr($new_pipes,-1,1) = "\\";
622              
623 4         5 $new_pipes = $init_space . $new_pipes . $end_space;
624             # substr($new_pipes, int((length($new_pipes)), 1)) / 2) = "^"; # feh
625             }
626              
627             # Now tack on the formatting for this node.
628 30 50 66     65 if($o->{'v_compact'} == 2) {
    100          
629 0 0       0 if(@daughters == 1) {
630 0         0 unshift @box, "|", $printable_name;
631             } else {
632 0         0 unshift @box, "|", $printable_name, $new_pipes;
633             }
634             } elsif ($o->{'v_compact'} == 1 and @daughters == 1) {
635 26         41 unshift @box, "|", $printable_name;
636             } else { # general case
637 4         8 unshift @box, "|", $printable_name, $new_pipes;
638             }
639             }
640              
641             # Flush the edges:
642 46         42 my $max_width = 0;
643 46         43 foreach my $line (@box) {
644 223         185 my $w = length($line);
645 223 100       277 $max_width = $w if $w > $max_width;
646             }
647 46         39 foreach my $one (@box) {
648 223         176 my $space_to_add = $max_width - length($one);
649 223 100       250 next unless $space_to_add;
650 50         59 my $add_left = int($space_to_add / 2);
651 50         38 my $add_right = $space_to_add - $add_left;
652 50         77 $one = (' ' x $add_left) . $one . (' ' x $add_right);
653             }
654              
655 46         97 return \@box; # must not return a null list!
656             }
657              
658             # -----------------------------------------------
659              
660             sub dump_names {
661 0     0 1 0 my($it, $o) = @_[0,1];
662 0 0       0 $o = {} unless ref $o;
663 0         0 my @out = ();
664 0   0     0 $o->{'_depth'} ||= 0;
665 0   0     0 $o->{'indent'} ||= ' ';
666 0   0     0 $o->{'tick'} ||= '';
667              
668             $o->{'callback'} = sub {
669 0     0   0 my($this, $o) = @_[0,1];
670             push(@out,
671             join('',
672             $o->{'indent'} x $o->{'_depth'},
673 0 0       0 $o->{'tick'},
674             defined $this->name ? $this->name : $this,
675             "\n"
676             )
677             );
678 0         0 return 1;
679             }
680 0         0 ;
681 0         0 $it->walk_down($o);
682 0         0 return @out;
683             }
684              
685             # -----------------------------------------------
686              
687             sub format_node
688             {
689 466     466 1 980 my($self, $options, $node) = @_;
690 466         1003 my($s) = $node -> name;
691 466 100       1505 $s .= $$options{no_attributes} ? '. Attributes: {}' : '. Attributes: ' . $self -> hashref2string($node -> attributes);
692              
693 466         2172 return $s;
694              
695             } # End of format_node.
696              
697             # -----------------------------------------------
698              
699             sub generation {
700 0     0 1 0 my($node, $limit) = @_[0,1];
701             return $node
702             if $node eq $limit || not(
703             defined($node->{'mother'}) &&
704 0 0 0     0 ref($node->{'mother'})
      0        
705             ); # bailout
706              
707 0         0 return map(@{$_->{'daughters'}}, $node->{'mother'}->generation($limit));
  0         0  
708             # recurse!
709             # Yup, my generation is just all the daughters of my mom's generation.
710             }
711              
712             # -----------------------------------------------
713              
714             sub generation_under {
715 0     0 1 0 my($node, @rest) = @_;
716 0         0 return $node->generation(@rest);
717             }
718              
719             # -----------------------------------------------
720              
721             sub hashref2string
722             {
723 332     332 1 636 my($self, $hashref) = @_;
724 332   50     725 $hashref ||= {};
725              
726 332 50       1724 return '{' . join(', ', map{$_ = 'undef' if (! defined($_) ); $$hashref{$_} = 'undef' if (! defined($$hashref{$_}) ); qq|$_ => "$$hashref{$_}"|} sort keys %$hashref) . '}';
  716 50       1500  
  716         1736  
  716         2974  
727              
728             } # End of hashref2string.
729              
730             # -----------------------------------------------
731              
732             sub _init { # method
733 445     445   772 my $this = shift;
734 445 50       1073 my $o = ref($_[0]) eq 'HASH' ? $_[0] : {};
735              
736             # Sane initialization.
737 445         1466 $this->_init_mother($o);
738 445         1209 $this->_init_daughters($o);
739 445         1458 $this->_init_name($o);
740 445         1268 $this->_init_attributes($o);
741              
742 445         818 return;
743             }
744              
745             # -----------------------------------------------
746              
747             sub _init_attributes { # to be called by an _init
748 445     445   896 my($this, $o) = @_[0,1];
749              
750 445         909 $this->{'attributes'} = {};
751              
752             # Undocumented and disfavored. Consider this just an example.
753 445 100       1598 $this->attributes( $o->{'attributes'} ) if exists $o->{'attributes'};
754             }
755              
756             # -----------------------------------------------
757              
758             sub _init_daughters { # to be called by an _init
759 469     469   930 my($this, $o) = @_[0,1];
760              
761 469         960 $this->{'daughters'} = [];
762              
763             # Undocumented and disfavored. Consider this just an example.
764 0         0 $this->set_daughters( @{$o->{'daughters'}} )
765 469 50 33     1377 if ref($o->{'daughters'}) && (@{$o->{'daughters'}});
  0         0  
766             # DO NOT use this option (as implemented) with new_daughter or
767             # new_daughter_left!!!!!
768             # BAD THINGS MAY HAPPEN!!!
769             }
770              
771             # -----------------------------------------------
772              
773             sub _init_mother { # to be called by an _init
774 469     469   1093 my($this, $o) = @_[0,1];
775              
776 469         1214 $this->{'mother'} = undef;
777              
778             # Undocumented and disfavored. Consider this just an example.
779             ( $o->{'mother'} )->add_daughter($this)
780 469 50 33     1516 if defined($o->{'mother'}) && ref($o->{'mother'});
781             # DO NOT use this option (as implemented) with new_daughter or
782             # new_daughter_left!!!!!
783             # BAD THINGS MAY HAPPEN!!!
784             }
785              
786             # -----------------------------------------------
787              
788             sub _init_name { # to be called by an _init
789 445     445   882 my($this, $o) = @_[0,1];
790              
791 445         841 $this->{'name'} = undef;
792              
793             # Undocumented and disfavored. Consider this just an example.
794 445 100       1586 $this->name( $o->{'name'} ) if exists $o->{'name'};
795             }
796              
797             # -----------------------------------------------
798              
799             sub is_daughter_of {
800 0     0 1 0 my($it,$mama) = @_[0,1];
801 0         0 return $it->{'mother'} eq $mama;
802             }
803              
804             # -----------------------------------------------
805              
806 0     0 1 0 sub is_node { return 1; } # always true.
807             # NEVER override this with anything that returns false in the belief
808             # that this'd signal "not a node class". The existence of this method
809             # is what I test for, with the various "can()" uses in this class.
810              
811             # -----------------------------------------------
812              
813             sub is_root
814             {
815 0     0 1 0 my($self) = @_;
816              
817 0 0       0 return defined $self -> mother ? 0 : 1;
818              
819             } # End of is_root.
820              
821             # -----------------------------------------------
822              
823             sub leaves_under {
824             # read-only method: return a list of all leaves under myself.
825             # Returns myself in the degenerate case of being a leaf myself.
826 0     0 1 0 my $node = shift;
827 0         0 my @List = ();
828             $node->walk_down({ 'callback' =>
829             sub {
830 0     0   0 my $node = $_[0];
831 0         0 my @daughters = @{$node->{'daughters'}};
  0         0  
832 0 0       0 push(@List, $node) unless @daughters;
833 0         0 return 1;
834             }
835 0         0 });
836 0 0       0 die "Spork Error 861: \@List has no contents!?!?" unless @List;
837             # impossible
838 0         0 return @List;
839             }
840              
841             # -----------------------------------------------
842              
843             sub left_sister {
844 0     0 1 0 my $it = $_[0];
845 0         0 my $mother = $it->{'mother'};
846 0 0       0 return undef unless $mother;
847 0         0 my @sisters = @{$mother->{'daughters'}};
  0         0  
848              
849 0 0       0 return undef if @sisters == 1; # I'm an only daughter
850              
851 0         0 my $left = undef;
852 0         0 foreach my $one (@sisters) {
853 0 0       0 return $left if $one eq $it;
854 0         0 $left = $one;
855             }
856 0         0 die "SPORK ERROR 9757: I'm not in my mother's daughter list!?!?";
857             }
858              
859             # -----------------------------------------------
860              
861             sub left_sisters {
862 0     0 1 0 my $it = $_[0];
863 0         0 my $mother = $it->{'mother'};
864 0 0       0 return() unless $mother;
865 0         0 my @sisters = @{$mother->{'daughters'}};
  0         0  
866 0 0       0 return() if @sisters == 1; # I'm an only daughter
867              
868 0         0 my @out = ();
869 0         0 foreach my $one (@sisters) {
870 0 0       0 return @out if $one eq $it;
871 0         0 push @out, $one;
872             }
873 0         0 die "SPORK ERROR 9767: I'm not in my mother's daughter list!?!?";
874             }
875              
876             # -----------------------------------------------
877              
878             sub lol_to_tree {
879 0     0 1 0 my($class, $lol, $seen_r) = @_[0,1,2];
880 0 0       0 $seen_r = {} unless ref($seen_r) eq 'HASH';
881 0 0 0     0 return if ref($lol) && $seen_r->{$lol}++; # catch circularity
882              
883 0   0     0 $class = ref($class) || $class;
884 0         0 my $node = $class->new();
885              
886 0 0       0 unless(ref($lol) eq 'ARRAY') { # It's a terminal node.
887 0 0       0 $node->name($lol) if defined $lol;
888 0         0 return $node;
889             }
890 0 0       0 return $node unless @$lol; # It's a terminal node, oddly represented
891              
892             # It's a non-terminal node.
893              
894 0         0 my @options = @$lol;
895 0 0       0 unless(ref($options[-1]) eq 'ARRAY') {
896             # This is what separates this method from simple_lol_to_tree
897 0         0 $node->name(pop(@options));
898             }
899              
900 0         0 foreach my $d (@options) { # Scan daughters (whether scalars or listrefs)
901 0         0 $node->add_daughter( $class->lol_to_tree($d, $seen_r) ); # recurse!
902             }
903              
904 0         0 return $node;
905             }
906              
907             # -----------------------------------------------
908              
909             sub mother { # read-only attrib-method: returns an object (the mother node)
910 466     466 1 747 my $this = shift;
911 466 50       1073 die "I'm a read-only method!" if @_;
912 466         1408 return $this->{'mother'};
913             }
914              
915             # -----------------------------------------------
916              
917             sub my_daughter_index {
918             # returns what number is my index in my mother's daughter list
919             # special case: 0 for root.
920 466     466 1 706 my $node = $_[0];
921 466         767 my $ord = -1;
922 466         838 my $mother = $node->{'mother'};
923              
924 466 100       994 return 0 unless $mother;
925 460         633 my @sisters = @{$mother->{'daughters'}};
  460         2269  
926              
927 460 50       993 die "SPORK ERROR 6512: My mother has no kids!!!" unless @sisters;
928              
929             Find_Self:
930 460         1130 for(my $i = 0; $i < @sisters; $i++) {
931 9935 100       31239 if($sisters[$i] eq $node) {
932 460         713 $ord = $i;
933 460         948 last Find_Self;
934             }
935             }
936 460 50       1007 die "SPORK ERROR 2837: I'm not a daughter of my mother?!?!" if $ord == -1;
937 460         1975 return $ord;
938             }
939              
940             # -----------------------------------------------
941              
942             sub name { # read/write attribute-method. returns/expects a scalar
943 1167     1167 1 1794 my $this = shift;
944 1167 100       2567 $this->{'name'} = $_[0] if @_;
945 1167         2480 return $this->{'name'};
946             }
947              
948             # -----------------------------------------------
949              
950             sub new { # constructor
951 445     445 1 376309 my $class = shift;
952 445 50       1131 $class = ref($class) if ref($class); # tchristic style. why not?
953              
954 445 100       1228 my $o = ref($_[0]) eq 'HASH' ? $_[0] : {}; # o for options hashref
955 445         1068 my $it = bless( {}, $class );
956 445 50       1184 print "Constructing $it in class $class\n" if $Debug;
957 445         1364 $it->_init( $o );
958 445         1297 return $it;
959             }
960              
961             # -----------------------------------------------
962              
963             sub new_daughter {
964 0     0 1 0 my($mother, @options) = @_;
965 0         0 my $daughter = $mother->new(@options);
966              
967 0         0 push @{$mother->{'daughters'}}, $daughter;
  0         0  
968 0         0 $daughter->{'mother'} = $mother;
969              
970 0         0 return $daughter;
971             }
972              
973             # -----------------------------------------------
974              
975             sub new_daughter_left {
976 0     0 1 0 my($mother, @options) = @_;
977 0         0 my $daughter = $mother->new(@options);
978              
979 0         0 unshift @{$mother->{'daughters'}}, $daughter;
  0         0  
980 0         0 $daughter->{'mother'} = $mother;
981              
982 0         0 return $daughter;
983             }
984              
985             # -----------------------------------------------
986              
987             sub node2string
988             {
989 466     466 1 964 my($self, $options, $node, $vert_dashes) = @_;
990 466   100     1110 my($depth) = scalar($node -> ancestors) || 0;
991 466 100       1002 my($sibling_count) = defined $node -> mother ? scalar $node -> self_and_sisters : 1;
992 466         952 my($offset) = ' ' x 5;
993 466 50       1078 my(@indent) = map{$$vert_dashes[$_] || $offset} 0 .. $depth - 1;
  770         2197  
994 466 100       1787 @$vert_dashes =
995             (
996             @indent,
997             ($sibling_count == 1 ? $offset : ' |'),
998             );
999              
1000 466 100       1084 if ($sibling_count == ($node -> my_daughter_index + 1) )
1001             {
1002 101         185 $$vert_dashes[$depth] = $offset;
1003             }
1004              
1005 466 100       1967 return join('' => @indent[1 .. $#indent]) . ($depth ? ' |--- ' : '') . $self -> format_node($options, $node);
1006              
1007             } # End of node2string.
1008              
1009             # -----------------------------------------------
1010              
1011             sub quote_name
1012             {
1013 0     0 1 0 my($self, $name) = @_;
1014              
1015 0         0 return "'$name'";
1016              
1017             } # End of quote_name.
1018              
1019             # -----------------------------------------------
1020              
1021             sub random_network { # constructor or method.
1022 0     0 1 0 my $class = $_[0];
1023 0 0       0 my $o = ref($_[1]) ? $_[1] : {};
1024 0         0 my $am_cons = 0;
1025 0         0 my $root;
1026              
1027 0 0       0 if(ref($class)){ # I'm a method.
1028 0         0 $root = $_[0]; # build under the given node, from same class.
1029 0         0 $class = ref $class;
1030 0         0 $am_cons = 0;
1031             } else { # I'm a constructor
1032 0         0 $root = $class->new; # build under a new node, with class named.
1033 0         0 $root->name("Root");
1034 0         0 $am_cons = 1;
1035             }
1036              
1037 0   0     0 my $min_depth = $o->{'min_depth'} || 2;
1038 0   0     0 my $max_depth = $o->{'max_depth'} || ($min_depth + 3);
1039 0   0     0 my $max_children = $o->{'max_children'} || 4;
1040 0   0     0 my $max_node_count = $o->{'max_node_count'} || 25;
1041              
1042 0 0       0 die "max_children has to be positive" if int($max_children) < 1;
1043              
1044 0         0 my @mothers = ( $root );
1045 0         0 my @children = ( );
1046 0         0 my $node_count = 1; # the root
1047              
1048             Gen:
1049 0         0 foreach my $depth (1 .. $max_depth) {
1050 0 0       0 last if $node_count > $max_node_count;
1051             Mother:
1052 0         0 foreach my $mother (@mothers) {
1053 0 0       0 last Gen if $node_count > $max_node_count;
1054 0         0 my $children_number;
1055 0 0       0 if($depth <= $min_depth) {
1056 0         0 until( $children_number = int(rand(1 + $max_children)) ) {}
1057             } else {
1058 0         0 $children_number = int(rand($max_children));
1059             }
1060             Beget:
1061 0         0 foreach (1 .. $children_number) {
1062 0 0       0 last Gen if $node_count > $max_node_count;
1063 0         0 my $node = $mother->new_daughter;
1064 0         0 $node->name("Node$node_count");
1065 0         0 ++$node_count;
1066 0         0 push(@children, $node);
1067             }
1068             }
1069 0         0 @mothers = @children;
1070 0         0 @children = ();
1071 0 0       0 last unless @mothers;
1072             }
1073              
1074 0         0 return $root;
1075             }
1076              
1077             # -----------------------------------------------
1078              
1079             sub read_attributes
1080             {
1081 420     420 1 2468 my($self, $s) = @_;
1082              
1083 420         999 my($attributes);
1084             my($name);
1085              
1086 420 50       3543 if ($s =~ /^(.+)\. Attributes: (\{.*\})$/)
1087             {
1088 420         1375 ($name, $attributes) = ($1, $self -> string2hashref($2) );
1089             }
1090             else
1091             {
1092 0         0 ($name, $attributes) = ($s, {});
1093             }
1094              
1095 420         2281 return Tree::DAG_Node -> new({name => $name, attributes => $attributes});
1096              
1097             } # End of read_attributes.
1098              
1099             # -----------------------------------------------
1100              
1101             sub read_tree
1102             {
1103 4     4 1 18764 my($self, $file_name) = @_;
1104 4         36 my($count) = 0;
1105 4         15 my($last_indent) = 0;
1106 4         10 my($test_string) = '--- ';
1107 4         10 my($test_length) = length $test_string;
1108              
1109 4         34 my($indent);
1110             my($node);
1111 4         0 my($offset);
1112 4         0 my($root);
1113 4         0 my(@stack);
1114 4         0 my($tos);
1115              
1116 4         19 for my $line (read_lines($file_name) )
1117             {
1118             # Ensure inter-OS compatability.
1119              
1120 420         2596 $line =~ s/\r$//g;
1121              
1122 420         753 $count++;
1123              
1124 420 100       1149 if ($count == 1)
1125             {
1126 4         22 $root = $node = $self -> read_attributes($line);
1127             }
1128             else
1129             {
1130 416         1957 $indent = index($line, $test_string);
1131              
1132 416 100       1181 if ($indent > $last_indent)
    100          
1133             {
1134 65         109 $tos = $node;
1135              
1136 65         158 push @stack, $node, $indent;
1137             }
1138             elsif ($indent < $last_indent)
1139             {
1140 53         88 $offset = $last_indent;
1141              
1142 53         181 while ($offset > $indent)
1143             {
1144 110         183 $offset = pop @stack;
1145 110         266 $tos = pop @stack;
1146             }
1147              
1148 53         139 push @stack, $tos, $offset;
1149             }
1150              
1151             # Warning: The next line must set $node.
1152             # Don't put the RHS into the call to add_daughter()!
1153              
1154 416         1814 $node = $self -> read_attributes(substr($line, $indent + $test_length) );
1155 416         1474 $last_indent = $indent;
1156              
1157 416         1061 $tos -> add_daughter($node);
1158             }
1159             }
1160              
1161 4         216 return $root;
1162              
1163             } # End of read_tree.
1164              
1165             # -----------------------------------------------
1166              
1167             sub remove_daughters { # write-only method
1168 13     13 1 16 my($mother, @daughters) = @_;
1169 13 50       25 die "mother must be an object!" unless ref $mother;
1170 13 50       14 return unless @daughters;
1171              
1172 13         13 my %to_delete;
1173 13         14 @daughters = grep {ref($_)
1174             and defined($_->{'mother'})
1175 13 50 33     45 and $mother eq $_->{'mother'}
1176             } @daughters;
1177 13 50       17 return unless @daughters;
1178 13         18 @to_delete{ @daughters } = undef;
1179              
1180             # This could be done better and more efficiently, I guess.
1181 13         13 foreach my $daughter (@daughters) {
1182 13         16 $daughter->{'mother'} = undef;
1183             }
1184 13         14 my $them = $mother->{'daughters'};
1185 13         13 @$them = grep { !exists($to_delete{$_}) } @$them;
  41         65  
1186              
1187             # $mother->_update_daughter_links; # unnecessary
1188 13         20 return;
1189             }
1190              
1191             # -----------------------------------------------
1192              
1193             sub remove_daughter { # alias
1194 4     4 1 9 my($it,@them) = @_; $it->remove_daughters(@them);
  4         5  
1195             }
1196              
1197             # -----------------------------------------------
1198              
1199             sub replace_with { # write-only method
1200 7     7 1 9 my($this, @replacements) = @_;
1201              
1202 7 50 33     26 if(not( defined($this->{'mother'}) && ref($this->{'mother'}) )) { # if root
1203 0         0 foreach my $replacement (@replacements) {
1204             $replacement->{'mother'}->remove_daughters($replacement)
1205 0 0       0 if $replacement->{'mother'};
1206             }
1207             # make 'em roots
1208             } else { # I have a mother
1209 7         9 my $mother = $this->{'mother'};
1210              
1211             #@replacements = grep(($_ eq $this || $_->{'mother'} ne $mother),
1212             # @replacements);
1213 7         9 @replacements = grep { $_ eq $this
1214             || not(defined($_->{'mother'}) &&
1215             ref($_->{'mother'}) &&
1216 9 50 33     45 $_->{'mother'} eq $mother
1217             )
1218             }
1219             @replacements;
1220             # Eliminate sisters (but not self)
1221             # i.e., I want myself or things NOT with the same mother as myself.
1222              
1223             $mother->set_daughters( # old switcheroo
1224             map($_ eq $this ? (@replacements) : $_ ,
1225 7 50       8 @{$mother->{'daughters'}}
  7         24  
1226             )
1227             );
1228             # and set_daughters does all the checking and possible
1229             # unlinking
1230             }
1231 7         15 return($this, @replacements);
1232             }
1233              
1234             # -----------------------------------------------
1235              
1236             sub replace_with_daughters { # write-only method
1237 0     0 1 0 my($this) = $_[0]; # takes no params other than the self
1238 0         0 my $mother = $this->{'mother'};
1239 0 0 0     0 return($this, $this->clear_daughters)
1240             unless defined($mother) && ref($mother);
1241              
1242 0         0 my @daughters = $this->clear_daughters;
1243 0         0 my $sib_r = $mother->{'daughters'};
1244 0 0       0 @$sib_r = map($_ eq $this ? (@daughters) : $_,
1245             @$sib_r # old switcheroo
1246             );
1247 0         0 foreach my $daughter (@daughters) {
1248 0         0 $daughter->{'mother'} = $mother;
1249             }
1250 0         0 return($this, @daughters);
1251             }
1252              
1253             # -----------------------------------------------
1254              
1255             sub right_sister {
1256 0     0 1 0 my $it = $_[0];
1257 0         0 my $mother = $it->{'mother'};
1258 0 0       0 return undef unless $mother;
1259 0         0 my @sisters = @{$mother->{'daughters'}};
  0         0  
1260 0 0       0 return undef if @sisters == 1; # I'm an only daughter
1261              
1262 0         0 my $seen = 0;
1263 0         0 foreach my $one (@sisters) {
1264 0 0       0 return $one if $seen;
1265 0 0       0 $seen = 1 if $one eq $it;
1266             }
1267 0 0       0 die "SPORK ERROR 9777: I'm not in my mother's daughter list!?!?"
1268             unless $seen;
1269 0         0 return undef;
1270             }
1271              
1272             # -----------------------------------------------
1273              
1274             sub right_sisters {
1275 0     0 1 0 my $it = $_[0];
1276 0         0 my $mother = $it->{'mother'};
1277 0 0       0 return() unless $mother;
1278 0         0 my @sisters = @{$mother->{'daughters'}};
  0         0  
1279 0 0       0 return() if @sisters == 1; # I'm an only daughter
1280              
1281 0         0 my @out;
1282 0         0 my $seen = 0;
1283 0         0 foreach my $one (@sisters) {
1284 0 0       0 push @out, $one if $seen;
1285 0 0       0 $seen = 1 if $one eq $it;
1286             }
1287 0 0       0 die "SPORK ERROR 9787: I'm not in my mother's daughter list!?!?"
1288             unless $seen;
1289 0         0 return @out;
1290             }
1291              
1292             # -----------------------------------------------
1293              
1294             sub root {
1295 0     0 1 0 my $it = $_[0];
1296 0         0 my @ancestors = ($it, $it->ancestors);
1297 0         0 return $ancestors[-1];
1298             }
1299              
1300             # -----------------------------------------------
1301              
1302             sub self_and_descendants {
1303             # read-only method: return a list of myself and any/all descendants
1304 0     0 1 0 my $node = shift;
1305 0         0 my @List = ();
1306 0     0   0 $node->walk_down({ 'callback' => sub { push @List, $_[0]; return 1;}});
  0         0  
  0         0  
1307 0 0       0 die "Spork Error 919: \@List has no contents!?!?" unless @List;
1308             # impossible
1309 0         0 return @List;
1310             }
1311              
1312             # -----------------------------------------------
1313              
1314             sub self_and_sisters {
1315 460     460 1 745 my $node = $_[0];
1316 460         793 my $mother = $node->{'mother'};
1317 460 50 33     1699 return $node unless defined($mother) && ref($mother); # special case
1318 460         663 return @{$node->{'mother'}->{'daughters'}};
  460         1099  
1319             }
1320              
1321             # -----------------------------------------------
1322              
1323             sub set_daughters { # write-only method
1324 22     22 1 24 my($mother, @them) = @_;
1325 22         33 $mother->clear_daughters;
1326 22 50       33 $mother->add_daughters(@them) if @them;
1327             # yup, it's that simple
1328             }
1329              
1330             # -----------------------------------------------
1331              
1332             sub simple_lol_to_tree {
1333 0     0 1 0 my($class, $lol, $seen_r) = @_[0,1,2];
1334 0   0     0 $class = ref($class) || $class;
1335 0 0       0 $seen_r = {} unless ref($seen_r) eq 'HASH';
1336 0 0 0     0 return if ref($lol) && $seen_r->{$lol}++; # catch circularity
1337              
1338 0         0 my $node = $class->new();
1339              
1340 0 0       0 unless(ref($lol) eq 'ARRAY') { # It's a terminal node.
1341 0 0       0 $node->name($lol) if defined $lol;
1342 0         0 return $node;
1343             }
1344              
1345             # It's a non-terminal node.
1346 0         0 foreach my $d (@$lol) { # scan daughters (whether scalars or listrefs)
1347 0         0 $node->add_daughter( $class->simple_lol_to_tree($d, $seen_r) ); # recurse!
1348             }
1349              
1350 0         0 return $node;
1351             }
1352              
1353             # -----------------------------------------------
1354              
1355             sub sisters {
1356 0     0 1 0 my $node = $_[0];
1357 0         0 my $mother = $node->{'mother'};
1358 0 0       0 return() unless $mother; # special case
1359             return grep($_ ne $node,
1360 0         0 @{$node->{'mother'}->{'daughters'}}
  0         0  
1361             );
1362             }
1363              
1364             # -----------------------------------------------
1365              
1366             sub string2hashref
1367             {
1368 420     420 1 1459 my($self, $s) = @_;
1369 420   50     1175 $s ||= '';
1370 420         861 my($result) = {};
1371              
1372 420         830 my($k);
1373             my($v);
1374              
1375 420 50       984 if ($s)
1376             {
1377             # Expect:
1378             # 1: The presence of the comma in "(',')" complicates things, so we can't use split(/\s*,\s*/, $s).
1379             # {x => "(',')"}
1380             # 2: The presence of "=>" complicates things, so we can't use split(/\s*=>\s*/).
1381             # {x => "=>"}
1382             # 3: So, assume ', ' is the outer separator, and then ' => ' is the inner separator.
1383              
1384             # Firstly, clean up the input, just to be safe.
1385             # None of these will match output from hashref2string($h).
1386              
1387 420         2553 $s =~ s/^\s*\{*//;
1388 420         3490 $s =~ s/\s*\}\s*$/\}/;
1389 420         960 my($finished) = 0;
1390              
1391             # The first '\' is for UltraEdit's syntax hiliting.
1392              
1393 420         1726 my($reg_exp) =
1394             qr/
1395             ([\"'])([^"']*?)\1\s*=>\s*(["'])([^"']*?)\3,?\s*
1396             |
1397             (["'])([^"']*?)\5\s*=>\s*(.*?),?\s*
1398             |
1399             (.*?)\s*=>\s*(["'])([^"']*?)\9,?\s*
1400             |
1401             (.*?)\s*=>\s*(.*?),?\s*
1402             /sx;
1403              
1404 420         708 my(@got);
1405              
1406 420         1083 while (! $finished)
1407             {
1408 1100 100       8578 if ($s =~ /$reg_exp/gc)
1409             {
1410 680 50       4029 push @got, defined($2) ? ($2, $4) : defined($6) ? ($6, $7) : defined($8) ? ($8, $10) : ($11, $12);
    50          
    50          
1411             }
1412             else
1413             {
1414 420         1033 $finished = 1;
1415             }
1416             }
1417              
1418 420         2601 $result = {@got};
1419             }
1420              
1421 420         1848 return $result;
1422              
1423             } # End of string2hashref.
1424              
1425             # -----------------------------------------------
1426              
1427             sub tree_to_lol {
1428             # I haven't /rigorously/ tested this.
1429 0     0 1 0 my($it, $o) = @_[0,1]; # $o is currently unused anyway
1430 0 0       0 $o = {} unless ref $o;
1431              
1432 0         0 my $out = [];
1433 0         0 my @lol_stack = ($out);
1434             $o->{'callback'} = sub {
1435 0     0   0 my($this, $o) = @_[0,1];
1436 0         0 my $new = [];
1437 0         0 push @{$lol_stack[-1]}, $new;
  0         0  
1438 0         0 push(@lol_stack, $new);
1439 0         0 return 1;
1440             }
1441 0         0 ;
1442             $o->{'callbackback'} = sub {
1443 0     0   0 my($this, $o) = @_[0,1];
1444 0 0       0 my $name = defined $this->name ? $it -> quote_name($this->name) : 'undef';
1445 0         0 push @{$lol_stack[-1]}, $name;
  0         0  
1446 0         0 pop @lol_stack;
1447 0         0 return 1;
1448             }
1449 0         0 ;
1450 0         0 $it->walk_down($o);
1451 0 0       0 die "totally bizarre error 12416" unless ref($out->[0]);
1452 0         0 $out = $out->[0]; # the real root
1453 0         0 return $out;
1454             }
1455              
1456             # -----------------------------------------------
1457              
1458             sub tree_to_lol_notation {
1459 0     0 1 0 my($it, $o) = @_[0,1];
1460 0 0       0 $o = {} unless ref $o;
1461 0         0 my @out = ();
1462 0   0     0 $o->{'_depth'} ||= 0;
1463 0 0       0 $o->{'multiline'} = 0 unless exists($o->{'multiline'});
1464              
1465 0         0 my $line_end;
1466 0 0       0 if($o->{'multiline'}) {
1467 0   0     0 $o->{'indent'} ||= ' ';
1468 0         0 $line_end = "\n";
1469             } else {
1470 0   0     0 $o->{'indent'} ||= '';
1471 0         0 $line_end = '';
1472             }
1473              
1474             $o->{'callback'} = sub {
1475 0     0   0 my($this, $o) = @_[0,1];
1476             push(@out,
1477 0         0 $o->{'indent'} x $o->{'_depth'},
1478             "[$line_end",
1479             );
1480 0         0 return 1;
1481             }
1482 0         0 ;
1483             $o->{'callbackback'} = sub {
1484 0     0   0 my($this, $o) = @_[0,1];
1485 0 0       0 my $name = defined $this->name ? $it -> quote_name($this->name) : 'undef';
1486             push(@out,
1487             $o->{'indent'} x ($o->{'_depth'} + 1),
1488             "$name$line_end",
1489 0         0 $o->{'indent'} x $o->{'_depth'},
1490             "],$line_end",
1491             );
1492 0         0 return 1;
1493             }
1494 0         0 ;
1495 0         0 $it->walk_down($o);
1496 0         0 return join('', @out);
1497             }
1498              
1499             # -----------------------------------------------
1500              
1501             sub tree_to_simple_lol {
1502             # I haven't /rigorously/ tested this.
1503 0     0 1 0 my $root = $_[0];
1504              
1505 0 0       0 return $root->name unless scalar($root->daughters);
1506             # special case we have to nip in the bud
1507              
1508 0         0 my($it, $o) = @_[0,1]; # $o is currently unused anyway
1509 0 0       0 $o = {} unless ref $o;
1510              
1511 0         0 my $out = [];
1512 0         0 my @lol_stack = ($out);
1513             $o->{'callback'} = sub {
1514 0     0   0 my($this, $o) = @_[0,1];
1515 0         0 my $new;
1516 0 0       0 my $name = defined $this->name ? $it -> quote_name($this->name) : 'undef';
1517 0 0       0 $new = scalar($this->daughters) ? [] : $name;
1518             # Terminal nodes are scalars, the rest are listrefs we'll fill in
1519             # as we recurse the tree below here.
1520 0         0 push @{$lol_stack[-1]}, $new;
  0         0  
1521 0         0 push(@lol_stack, $new);
1522 0         0 return 1;
1523             }
1524 0         0 ;
1525 0     0   0 $o->{'callbackback'} = sub { pop @lol_stack; return 1; };
  0         0  
  0         0  
1526 0         0 $it->walk_down($o);
1527 0 0       0 die "totally bizarre error 12416" unless ref($out->[0]);
1528 0         0 $out = $out->[0]; # the real root
1529 0         0 return $out;
1530             }
1531              
1532             # -----------------------------------------------
1533              
1534             sub tree_to_simple_lol_notation {
1535 0     0 1 0 my($it, $o) = @_[0,1];
1536 0 0       0 $o = {} unless ref $o;
1537 0         0 my @out = ();
1538 0   0     0 $o->{'_depth'} ||= 0;
1539 0 0       0 $o->{'multiline'} = 0 unless exists($o->{'multiline'});
1540              
1541 0         0 my $line_end;
1542 0 0       0 if($o->{'multiline'}) {
1543 0   0     0 $o->{'indent'} ||= ' ';
1544 0         0 $line_end = "\n";
1545             } else {
1546 0   0     0 $o->{'indent'} ||= '';
1547 0         0 $line_end = '';
1548             }
1549              
1550             $o->{'callback'} = sub {
1551 0     0   0 my($this, $o) = @_[0,1];
1552 0 0       0 if(scalar($this->daughters)) { # Nonterminal
1553             push(@out,
1554 0         0 $o->{'indent'} x $o->{'_depth'},
1555             "[$line_end",
1556             );
1557             } else { # Terminal
1558 0 0       0 my $name = defined $this->name ? $it -> quote_name($this->name) : 'undef';
1559             push @out,
1560 0         0 $o->{'indent'} x $o->{'_depth'},
1561             "$name,$line_end";
1562             }
1563 0         0 return 1;
1564             }
1565 0         0 ;
1566             $o->{'callbackback'} = sub {
1567 0     0   0 my($this, $o) = @_[0,1];
1568             push(@out,
1569 0 0       0 $o->{'indent'} x $o->{'_depth'},
1570             "], $line_end",
1571             ) if scalar($this->daughters);
1572 0         0 return 1;
1573             }
1574 0         0 ;
1575              
1576 0         0 $it->walk_down($o);
1577 0         0 return join('', @out);
1578             }
1579              
1580             # -----------------------------------------------
1581              
1582             sub tree2string
1583             {
1584 6     6 1 2253 my($self, $options, $tree) = @_;
1585 6   100     30 $options ||= {};
1586 6   100     33 $$options{no_attributes} ||= 0;
1587 6   33     29 $tree ||= $self;
1588              
1589 6         10 my(@out);
1590             my(@vert_dashes);
1591              
1592             $tree -> walk_down
1593             ({
1594             callback =>
1595             sub
1596             {
1597 466     466   818 my($node) = @_;
1598              
1599 466         1182 push @out, $self -> node2string($options, $node, \@vert_dashes);
1600              
1601 466         972 return 1,
1602             },
1603 6         77 _depth => 0,
1604             });
1605              
1606 6         201 return [@out];
1607              
1608             } # End of tree2string.
1609              
1610             # -----------------------------------------------
1611              
1612             sub unlink_from_mother {
1613 0     0 1 0 my $node = $_[0];
1614 0         0 my $mother = $node->{'mother'};
1615 0 0 0     0 $mother->remove_daughters($node) if defined($mother) && ref($mother);
1616 0         0 return $mother;
1617             }
1618              
1619             # -----------------------------------------------
1620              
1621             sub _update_daughter_links {
1622             # Eliminate any duplicates in my daughters list, and update
1623             # all my daughters' links to myself.
1624 465     465   759 my $this = shift;
1625              
1626 465         806 my $them = $this->{'daughters'};
1627              
1628             # Eliminate duplicate daughters.
1629 465         871 my %seen = ();
1630 465 50       1159 @$them = grep { ref($_) && not($seen{$_}++) } @$them;
  9932         41336  
1631             # not that there should ever be duplicate daughters anyhoo.
1632              
1633 465         1103 foreach my $one (@$them) { # linkage bookkeeping
1634 9932 50       19929 die "daughter <$one> isn't an object!" unless ref $one;
1635 9932         17877 $one->{'mother'} = $this;
1636             }
1637 465         2866 return;
1638             }
1639              
1640             # -----------------------------------------------
1641              
1642             sub walk_down {
1643 557     557 1 1202 my($this, $o) = @_[0,1];
1644              
1645             # All the can()s are in case an object changes class while I'm
1646             # looking at it.
1647              
1648 557 50       1052 die "I need options!" unless ref($o);
1649             die "I need a callback or a callbackback" unless
1650 557 50 33     1337 ( ref($o->{'callback'}) || ref($o->{'callbackback'}) );
1651              
1652 557 50       1157 my $callback = ref($o->{'callback'}) ? $o->{'callback'} : undef;
1653 557 50       1051 my $callbackback = ref($o->{'callbackback'}) ? $o->{'callbackback'} : undef;
1654 557         775 my $callback_status = 1;
1655              
1656 557 50       999 print "Callback: $callback Callbackback: $callbackback\n" if $Debug;
1657              
1658 557 50 0     966 printf "* Entering %s\n", ($this->name || $this) if $Debug;
1659 557 50       1189 $callback_status = &{ $callback }( $this, $o ) if $callback;
  557         1077  
1660              
1661 557 50       1249 if($callback_status) {
1662             # Keep recursing unless callback returned false... and if there's
1663             # anything to recurse into, of course.
1664 557 50       1652 my @daughters = UNIVERSAL::can($this, 'is_node') ? @{$this->{'daughters'}} : ();
  557         1287  
1665 557 100       1181 if(@daughters) {
1666 155         207 $o->{'_depth'} += 1;
1667             #print "Depth " , $o->{'_depth'}, "\n";
1668 155         223 foreach my $one (@daughters) {
1669 548 50       2033 $one->walk_down($o) if UNIVERSAL::can($one, 'is_node');
1670             # and if it can do "is_node", it should provide a walk_down!
1671             }
1672 155         271 $o->{'_depth'} -= 1;
1673             }
1674             } else {
1675 0 0 0     0 printf "* Recursing below %s pruned\n", ($this->name || $this) if $Debug;
1676             }
1677              
1678             # Note that $callback_status doesn't block callbackback from being called
1679 557 50       1150 if($callbackback){
1680 0 0       0 if(UNIVERSAL::can($this, 'is_node')) { # if it's still a node!
1681 0 0       0 print "* Calling callbackback\n" if $Debug;
1682 0         0 scalar( &{ $callbackback }( $this, $o ) );
  0         0  
1683             # scalar to give it the same context as callback
1684             } else {
1685 0 0       0 print "* Can't call callbackback -- $this isn't a node anymore\n"
1686             if $Debug;
1687             }
1688             }
1689 557 50       1039 if($Debug) {
1690 0 0       0 if(UNIVERSAL::can($this, 'is_node')) { # if it's still a node!
1691 0   0     0 printf "* Leaving %s\n", ($this->name || $this)
1692             } else {
1693 0         0 print "* Leaving [no longer a node]\n";
1694             }
1695             }
1696 557         1200 return;
1697             }
1698              
1699             # -----------------------------------------------
1700              
1701             1;
1702              
1703             =pod
1704              
1705             =encoding utf-8
1706              
1707             =head1 NAME
1708              
1709             Tree::DAG_Node - An N-ary tree
1710              
1711             =head1 SYNOPSIS
1712              
1713             =head2 Using as a base class
1714              
1715             package Game::Tree::Node;
1716              
1717             use parent 'Tree::DAG_Node';
1718              
1719             # Now add your own methods overriding/extending the methods in C...
1720              
1721             =head2 Using as a class on its own
1722              
1723             use Tree::DAG_Node;
1724              
1725             my($root) = Tree::DAG_Node -> new({name => 'root', attributes => {uid => 0} });
1726              
1727             $root -> add_daughter(Tree::DAG_Node -> new({name => 'one', attributes => {uid => 1} }) );
1728             $root -> add_daughter(Tree::DAG_Node -> new({name => 'two', attributes => {} }) );
1729             $root -> add_daughter(Tree::DAG_Node -> new({name => 'three'}) ); # Attrs default to {}.
1730              
1731             Or:
1732              
1733             my($count) = 0;
1734             my($tree) = Tree::DAG_Node -> new({name => 'Root', attributes => {'uid' => $count} });
1735              
1736             Or:
1737              
1738             my $root = Tree::DAG_Node -> new();
1739              
1740             $root -> name("I'm the tops");
1741             $root -> attributes({uid => 0});
1742              
1743             my $new_daughter = $root -> new_daughter;
1744              
1745             $new_daughter -> name('Another node');
1746             $new_daughter -> attributes({uid => 1});
1747             ...
1748              
1749             Lastly, for fancy wrappers - called _add_daughter() - around C, see these modules:
1750             L and L. Both of these modules use L.
1751              
1752             See scripts/*.pl for other samples.
1753              
1754             =head2 Using with utf-8 data
1755              
1756             read_tree($file_name) works with utf-8 data. See t/read.tree.t and t/tree.utf8.attributes.txt.
1757             Such a file can be created by redirecting the output of tree2string() to a file of type utf-8.
1758              
1759             See the docs for L for the difference between utf8 and utf-8. In brief, use utf-8.
1760              
1761             See also scripts/write_tree.pl and scripts/read.tree.pl and scripts/read.tree.log.
1762              
1763             =head1 DESCRIPTION
1764              
1765             This class encapsulates/makes/manipulates objects that represent nodes
1766             in a tree structure. The tree structure is not an object itself, but
1767             is emergent from the linkages you create between nodes. This class
1768             provides the methods for making linkages that can be used to build up
1769             a tree, while preventing you from ever making any kinds of linkages
1770             which are not allowed in a tree (such as having a node be its own
1771             mother or ancestor, or having a node have two mothers).
1772              
1773             This is what I mean by a "tree structure", a bit redundantly stated:
1774              
1775             =over 4
1776              
1777             =item o A tree is a special case of an acyclic directed graph
1778              
1779             =item o A tree is a network of nodes where there's exactly one root node
1780              
1781             Also, the only primary relationship between nodes is the mother-daughter relationship.
1782              
1783             =item o No node can be its own mother, or its mother's mother, etc
1784              
1785             =item o Each node in the tree has exactly one parent
1786              
1787             Except for the root of course, which is parentless.
1788              
1789             =item o Each node can have any number (0 .. N) daughter nodes
1790              
1791             A given node's daughter nodes constitute an I list.
1792              
1793             However, you are free to consider this ordering irrelevant.
1794             Some applications do need daughters to be ordered, so I chose to
1795             consider this the general case.
1796              
1797             =item o A node can appear in only one tree, and only once in that tree
1798              
1799             Notably (notable because it doesn't follow from the two above points),
1800             a node cannot appear twice in its mother's daughter list.
1801              
1802             =item o There's an idea of up versus down
1803              
1804             Up means towards to the root, and down means away from the root (and towards the leaves).
1805              
1806             =item o There's an idea of left versus right
1807              
1808             Left is toward the start (index 0) of a given node's daughter list, and right is toward the end of a
1809             given node's daughter list.
1810              
1811             =back
1812              
1813             Trees as described above have various applications, among them:
1814             representing syntactic constituency, in formal linguistics;
1815             representing contingencies in a game tree; representing abstract
1816             syntax in the parsing of any computer language -- whether in
1817             expression trees for programming languages, or constituency in the
1818             parse of a markup language document. (Some of these might not use the
1819             fact that daughters are ordered.)
1820              
1821             (Note: B-Trees are a very special case of the above kinds of trees,
1822             and are best treated with their own class. Check CPAN for modules
1823             encapsulating B-Trees; or if you actually want a database, and for
1824             some reason ended up looking here, go look at L.)
1825              
1826             Many base classes are not usable except as such -- but C
1827             can be used as a normal class. You can go ahead and say:
1828              
1829             use Tree::DAG_Node;
1830             my $root = Tree::DAG_Node->new();
1831             $root->name("I'm the tops");
1832             $new_daughter = Tree::DAG_Node->new();
1833             $new_daughter->name("More");
1834             $root->add_daughter($new_daughter);
1835              
1836             and so on, constructing and linking objects from C and
1837             making useful tree structures out of them.
1838              
1839             =head1 A NOTE TO THE READER
1840              
1841             This class is big and provides lots of methods. If your problem is
1842             simple (say, just representing a simple parse tree), this class might
1843             seem like using an atomic sledgehammer to swat a fly. But the
1844             complexity of this module's bells and whistles shouldn't detract from
1845             the efficiency of using this class for a simple purpose. In fact, I'd
1846             be very surprised if any one user ever had use for more that even a
1847             third of the methods in this class. And remember: an atomic
1848             sledgehammer B kill that fly.
1849              
1850             =head1 OBJECT CONTENTS
1851              
1852             Implementationally, each node in a tree is an object, in the sense of
1853             being an arbitrarily complex data structure that belongs to a class
1854             (presumably C, or ones derived from it) that provides
1855             methods.
1856              
1857             The attributes of a node-object are:
1858              
1859             =over
1860              
1861             =item o mother -- this node's mother. undef if this is a root
1862              
1863             =item o daughters -- the (possibly empty) list of daughters of this node
1864              
1865             =item o name -- the name for this node
1866              
1867             Need not be unique, or even printable. This is printed in some of the
1868             various dumper methods, but it's up to you if you don't put anything
1869             meaningful or printable here.
1870              
1871             =item o attributes -- whatever the user wants to use it for
1872              
1873             Presumably a hashref to whatever other attributes the user wants to
1874             store without risk of colliding with the object's real attributes.
1875             (Example usage: attributes to an SGML tag -- you definitely wouldn't
1876             want the existence of a "mother=foo" pair in such a tag to collide with
1877             a node object's 'mother' attribute.)
1878              
1879             Aside from (by default) initializing it to {}, and having the access
1880             method called "attributes" (described a ways below), I don't do
1881             anything with the "attributes" in this module. I basically intended
1882             this so that users who don't want/need to bother deriving a class
1883             from C, could still attach whatever data they wanted in a
1884             node.
1885              
1886             =back
1887              
1888             "mother" and "daughters" are attributes that relate to linkage -- they
1889             are never written to directly, but are changed as appropriate by the
1890             "linkage methods", discussed below.
1891              
1892             The other two (and whatever others you may add in derived classes) are
1893             simply accessed thru the same-named methods, discussed further below.
1894              
1895             =head2 About The Documented Interface
1896              
1897             Stick to the documented interface (and comments in the source --
1898             especially ones saying "undocumented!" and/or "disfavored!" -- do not
1899             count as documentation!), and don't rely on any behavior that's not in
1900             the documented interface.
1901              
1902             Specifically, unless the documentation for a particular method says
1903             "this method returns thus-and-such a value", then you should not rely on
1904             it returning anything meaningful.
1905              
1906             A I acquaintance with at least the broader details of the source
1907             code for this class is assumed for anyone using this class as a base
1908             class -- especially if you're overriding existing methods, and
1909             B if you're overriding linkage methods.
1910              
1911             =head1 MAIN CONSTRUCTOR, AND INITIALIZER
1912              
1913             =over
1914              
1915             =item the constructor CLASS->new() or CLASS->new($options)
1916              
1917             This creates a new node object, calls $object->_init($options)
1918             to provide it sane defaults (like: undef name, undef mother, no
1919             daughters, 'attributes' setting of a new empty hashref), and returns
1920             the object created. (If you just said "CLASS->new()" or "CLASS->new",
1921             then it pretends you called "CLASS->new({})".)
1922              
1923             See also the comments under L for options supported in the call to new().
1924              
1925             If you use C as a superclass, and you add
1926             attributes that need to be initialized, what you need to do is provide
1927             an _init method that calls $this->SUPER::_init($options) to use its
1928             superclass's _init method, and then initializes the new attributes:
1929              
1930             sub _init {
1931             my($this, $options) = @_[0,1];
1932             $this->SUPER::_init($options); # call my superclass's _init to
1933             # init all the attributes I'm inheriting
1934              
1935             # Now init /my/ new attributes:
1936             $this->{'amigos'} = []; # for example
1937             }
1938              
1939             =item the constructor $obj->new() or $obj->new($options)
1940              
1941             Just another way to get at the L method. This B
1942             $obj, but merely constructs a new object of the same class as it.
1943             Saves you the bother of going $class = ref $obj; $obj2 = $class->new;
1944              
1945             =item the method $node->_init($options)
1946              
1947             Initialize the object's attribute values. See the discussion above.
1948             Presumably this should be called only by the guts of the L
1949             constructor -- never by the end user.
1950              
1951             Currently there are no documented options for putting in the
1952             $options hashref, but (in case you want to disregard the above rant)
1953             the option exists for you to use $options for something useful
1954             in a derived class.
1955              
1956             Please see the source for more information.
1957              
1958             =item see also (below) the constructors "new_daughter" and "new_daughter_left"
1959              
1960             =back
1961              
1962             =head1 METHODS
1963              
1964             =head2 add_daughter(LIST)
1965              
1966             An exact synonym for L.
1967              
1968             =head2 add_daughters(LIST)
1969              
1970             This method adds the node objects in LIST to the (right) end of
1971             $mother's I list. Making a node N1 the daughter of another
1972             node N2 also means that N1's I attribute is "automatically" set
1973             to N2; it also means that N1 stops being anything else's daughter as
1974             it becomes N2's daughter.
1975              
1976             If you try to make a node its own mother, a fatal error results. If
1977             you try to take one of a node N1's ancestors and make it also a
1978             daughter of N1, a fatal error results. A fatal error results if
1979             anything in LIST isn't a node object.
1980              
1981             If you try to make N1 a daughter of N2, but it's B a daughter
1982             of N2, then this is a no-operation -- it won't move such nodes to the
1983             end of the list or anything; it just skips doing anything with them.
1984              
1985             =head2 add_daughter_left(LIST)
1986              
1987             An exact synonym for L.
1988              
1989             =head2 add_daughters_left(LIST)
1990              
1991             This method is just like L, except that it adds the
1992             node objects in LIST to the (left) beginning of $mother's daughter
1993             list, instead of the (right) end of it.
1994              
1995             =head2 add_left_sister(LIST)
1996              
1997             An exact synonym for L.
1998              
1999             =head2 add_left_sisters(LIST)
2000              
2001             This adds the elements in LIST (in that order) as immediate left sisters of
2002             $node. In other words, given that B's mother's daughter-list is (A,B,C,D),
2003             calling B->add_left_sisters(X,Y) makes B's mother's daughter-list
2004             (A,X,Y,B,C,D).
2005              
2006             If LIST is empty, this is a no-op, and returns empty-list.
2007              
2008             This is basically implemented as a call to $node->replace_with(LIST,
2009             $node), and so all replace_with's limitations and caveats apply.
2010              
2011             The return value of $node->add_left_sisters(LIST) is the elements of
2012             LIST that got added, as returned by replace_with -- minus the copies
2013             of $node you'd get from a straight call to $node->replace_with(LIST,
2014             $node).
2015              
2016             =head2 add_right_sister(LIST)
2017              
2018             An exact synonym for L.
2019              
2020             =head2 add_right_sisters(LIST)
2021              
2022             Just like add_left_sisters (which see), except that the elements
2023             in LIST (in that order) as immediate B sisters of $node;
2024              
2025             In other words, given that B's mother's daughter-list is (A,B,C,D),
2026             calling B->add_right_sisters(X,Y) makes B's mother's daughter-list
2027             (A,B,X,Y,C,D).
2028              
2029             =head2 address()
2030              
2031             =head2 address(ADDRESS)
2032              
2033             With the first syntax, returns the address of $node within its tree,
2034             based on its position within the tree. An address is formed by noting
2035             the path between the root and $node, and concatenating the
2036             daughter-indices of the nodes this passes thru (starting with 0 for
2037             the root, and ending with $node).
2038              
2039             For example, if to get from node ROOT to node $node, you pass thru
2040             ROOT, A, B, and $node, then the address is determined as:
2041              
2042             =over 4
2043              
2044             =item o ROOT's my_daughter_index is 0
2045              
2046             =item o A's my_daughter_index is, suppose, 2
2047              
2048             A is index 2 in ROOT's daughter list.
2049              
2050             =item o B's my_daughter_index is, suppose, 0
2051              
2052             B is index 0 in A's daughter list.
2053              
2054             =item o $node's my_daughter_index is, suppose, 4
2055              
2056             $node is index 4 in B's daughter list.
2057              
2058             =back
2059              
2060             The address of the above-described $node is, therefore, "0:2:0:4".
2061              
2062             (As a somewhat special case, the address of the root is always "0";
2063             and since addresses start from the root, all addresses start with a
2064             "0".)
2065              
2066             The second syntax, where you provide an address, starts from the root
2067             of the tree $anynode belongs to, and returns the node corresponding to
2068             that address. Returns undef if no node corresponds to that address.
2069             Note that this routine may be somewhat liberal in its interpretation
2070             of what can constitute an address; i.e., it accepts "0.2.0.4", besides
2071             "0:2:0:4".
2072              
2073             Also note that the address of a node in a tree is meaningful only in
2074             that tree as currently structured.
2075              
2076             (Consider how ($address1 cmp $address2) may be magically meaningful
2077             to you, if you meant to figure out what nodes are to the right of what
2078             other nodes.)
2079              
2080             =head2 ancestors()
2081              
2082             Returns the list of this node's ancestors, starting with its mother,
2083             then grandmother, and ending at the root. It does this by simply
2084             following the 'mother' attributes up as far as it can. So if $item IS
2085             the root, this returns an empty list.
2086              
2087             Consider that scalar($node->ancestors) returns the ply of this node
2088             within the tree -- 2 for a granddaughter of the root, etc., and 0 for
2089             root itself.
2090              
2091             =head2 attribute()
2092              
2093             =head2 attribute(SCALAR)
2094              
2095             Exact synonyms for L and L.
2096              
2097             =head2 attributes()
2098              
2099             =head2 attributes(SCALAR)
2100              
2101             In the first form, returns the value of the node object's "attributes"
2102             attribute. In the second form, sets it to the value of SCALAR. I
2103             intend this to be used to store a reference to a (presumably
2104             anonymous) hash the user can use to store whatever attributes he
2105             doesn't want to have to store as object attributes. In this case, you
2106             needn't ever set the value of this. (_init has already initialized it
2107             to {}.) Instead you can just do...
2108              
2109             $node->attributes->{'foo'} = 'bar';
2110              
2111             ...to write foo => bar.
2112              
2113             =head2 clear_daughters()
2114              
2115             This unlinks all $mother's daughters.
2116             Returns the list of what used to be $mother's daughters.
2117              
2118             Not to be confused with L.
2119              
2120             =head2 common(LIST)
2121              
2122             Returns the lowest node in the tree that is ancestor-or-self to the
2123             nodes $node and LIST.
2124              
2125             If the nodes are far enough apart in the tree, the answer is just the
2126             root.
2127              
2128             If the nodes aren't all in the same tree, the answer is undef.
2129              
2130             As a degenerate case, if LIST is empty, returns $node.
2131              
2132             =head2 common_ancestor(LIST)
2133              
2134             Returns the lowest node that is ancestor to all the nodes given (in
2135             nodes $node and LIST). In other words, it answers the question: "What
2136             node in the tree, as low as possible, is ancestor to the nodes given
2137             ($node and LIST)?"
2138              
2139             If the nodes are far enough apart, the answer is just the root --
2140             except if any of the nodes are the root itself, in which case the
2141             answer is undef (since the root has no ancestor).
2142              
2143             If the nodes aren't all in the same tree, the answer is undef.
2144              
2145             As a degenerate case, if LIST is empty, returns $node's mother;
2146             that'll be undef if $node is root.
2147              
2148             =head2 copy($option)
2149              
2150             Returns a copy of the calling node (the invocant). E.g.: my($copy) = $node -> copy;
2151              
2152             $option is a hashref of options, with these (key => value) pairs:
2153              
2154             =over 4
2155              
2156             =item o no_attribute_copy => $Boolean
2157              
2158             If set to 1, do not copy the node's attributes.
2159              
2160             If not specified, defaults to 0, which copies attributes.
2161              
2162             =back
2163              
2164             =head2 copy_at_and_under()
2165              
2166             =head2 copy_at_and_under($options)
2167              
2168             This returns a copy of the subtree consisting of $node and everything
2169             under it.
2170              
2171             If you pass no options, copy_at_and_under pretends you've passed {}.
2172              
2173             This works by recursively building up the new tree from the leaves,
2174             duplicating nodes using $orig_node->copy($options_ref) and then
2175             linking them up into a new tree of the same shape.
2176              
2177             Options you specify are passed down to calls to $node->copy.
2178              
2179             =head2 copy_tree()
2180              
2181             =head2 copy_tree($options)
2182              
2183             This returns the root of a copy of the tree that $node is a member of.
2184             If you pass no options, copy_tree pretends you've passed {}.
2185              
2186             This method is currently implemented as just a call to
2187             $this->root->copy_at_and_under($options), but magic may be
2188             added in the future.
2189              
2190             Options you specify are passed down to calls to $node->copy.
2191              
2192             =head2 daughters()
2193              
2194             This returns the (possibly empty) list of daughters for $node.
2195              
2196             =head2 decode_lol($lol)
2197              
2198             Returns an arrayref having decoded the deeply nested structure $lol.
2199              
2200             $lol will be the output of either tree_to_lol() or tree_to_simple_lol().
2201              
2202             See scripts/read.tree.pl, and it's output file scripts/read.tree.log.
2203              
2204             =head2 delete_tree()
2205              
2206             Destroys the entire tree that $node is a member of (starting at the
2207             root), by nulling out each node-object's attributes (including, most
2208             importantly, its linkage attributes -- hopefully this is more than
2209             sufficient to eliminate all circularity in the data structure), and
2210             then moving it into the class DEADNODE.
2211              
2212             Use this when you're finished with the tree in question, and want to
2213             free up its memory. (If you don't do this, it'll get freed up anyway
2214             when your program ends.)
2215              
2216             If you try calling any methods on any of the node objects in the tree
2217             you've destroyed, you'll get an error like:
2218              
2219             Can't locate object method "leaves_under"
2220             via package "DEADNODE".
2221              
2222             So if you see that, that's what you've done wrong. (Actually, the
2223             class DEADNODE does provide one method: a no-op method "delete_tree".
2224             So if you want to delete a tree, but think you may have deleted it
2225             already, it's safe to call $node->delete_tree on it (again).)
2226              
2227             The L method is needed because Perl's garbage collector
2228             would never (as currently implemented) see that it was time to
2229             de-allocate the memory the tree uses -- until either you call
2230             $node->delete_tree, or until the program stops (at "global
2231             destruction" time, when B is unallocated).
2232              
2233             Incidentally, there are better ways to do garbage-collecting on a
2234             tree, ways which don't require the user to explicitly call a method
2235             like L -- they involve dummy classes, as explained at
2236             L
2237              
2238             However, introducing a dummy class concept into C would
2239             be rather a distraction. If you want to do this with your derived
2240             classes, via a DESTROY in a dummy class (or in a tree-metainformation
2241             class, maybe), then feel free to.
2242              
2243             The only case where I can imagine L failing to totally
2244             void the tree, is if you use the hashref in the "attributes" attribute
2245             to store (presumably among other things) references to other nodes'
2246             "attributes" hashrefs -- which 1) is maybe a bit odd, and 2) is your
2247             problem, because it's your hash structure that's circular, not the
2248             tree's. Anyway, consider:
2249              
2250             # null out all my "attributes" hashes
2251             $anywhere->root->walk_down({
2252             'callback' => sub {
2253             $hr = $_[0]->attributes; %$hr = (); return 1;
2254             }
2255             });
2256             # And then:
2257             $anywhere->delete_tree;
2258              
2259             (I suppose L is a "destructor", or as close as you can
2260             meaningfully come for a circularity-rich data structure in Perl.)
2261              
2262             See also L.
2263              
2264             =head2 depth_under()
2265              
2266             Returns an integer representing the number of branches between this
2267             $node and the most distant leaf under it. (In other words, this
2268             returns the ply of subtree starting of $node. Consider
2269             scalar($it->ancestors) if you want the ply of a node within the whole
2270             tree.)
2271              
2272             =head2 descendants()
2273              
2274             Returns a list consisting of all the descendants of $node. Returns
2275             empty-list if $node is a terminal_node.
2276              
2277             (Note that it's spelled "descendants", not "descendents".)
2278              
2279             =head2 draw_ascii_tree([$options])
2280              
2281             Here, the [] refer to an optional parameter.
2282              
2283             Returns an arrayref of lines suitable for printing.
2284              
2285             Draws a nice ASCII-art representation of the tree structure.
2286              
2287             The tree looks like:
2288              
2289             |
2290            
2291             /-------+-----+---+---\
2292             | | | | |
2293            
2294             /---\ /---\ | | |
2295             | | | |
2296             | |
2297             | | | |
2298            
2299             | |
2300            
2301             | |
2302            
2303             | |
2304            
2305              
2306             See scripts/cut.and.paste.subtrees.pl.
2307              
2308             Example usage:
2309              
2310             print map("$_\n", @{$tree->draw_ascii_tree});
2311              
2312             I takes parameters you set in the $options hashref:
2313              
2314             =over 4
2315              
2316             =item o h_compact
2317              
2318             Takes 0 or 1. Sets the extent to which
2319             I tries to save horizontal space.
2320              
2321             If I think of a better scrunching algorithm, there'll be a "2" setting
2322             for this.
2323              
2324             Default: 1.
2325              
2326             =item o h_spacing
2327              
2328             Takes a number 0 or greater. Sets the number of spaces
2329             inserted horizontally between nodes (and groups of nodes) in a tree.
2330              
2331             Default: 1.
2332              
2333             =item o no_name
2334              
2335             If true, I doesn't print the name of
2336             the node; it simply prints a "*".
2337              
2338             Default: 0 (i.e., print the node name.)
2339              
2340             =item o v_compact
2341              
2342             Takes a number 0, 1, or 2. Sets the degree to which
2343             I tries to save vertical space. Defaults to 1.
2344              
2345             =back
2346              
2347             The code occasionally returns trees that are a bit cock-eyed in parts; if
2348             anyone can suggest a better drawing algorithm, I'd be appreciative.
2349              
2350             See also L.
2351              
2352             =head2 dump_names($options)
2353              
2354             Returns an array.
2355              
2356             Dumps, as an indented list, the names of the nodes starting at $node,
2357             and continuing under it. Options are:
2358              
2359             =over 4
2360              
2361             =item o _depth -- A nonnegative number
2362              
2363             Indicating the depth to consider $node as being at (and so the generation under that is that plus
2364             one, etc.). You may choose to use set _depth => scalar($node->ancestors).
2365              
2366             Default: 0.
2367              
2368             =item o tick -- a string to preface each entry with
2369              
2370             This string goes between the indenting-spacing and the node's name. You
2371             may prefer "*" or "-> " or something.
2372              
2373             Default: ''.
2374              
2375             =item o indent -- the string used to indent with
2376              
2377             Another sane value might be '. ' (period, space). Setting it to empty-string suppresses indenting.
2378              
2379             Default: ' ' x 2.
2380              
2381             =back
2382              
2383             The output is not printed, but is returned as a list, where each
2384             item is a line, with a "\n" at the end.
2385              
2386             =head2 format_node($options, $node)
2387              
2388             Returns a string consisting of the node's name and, optionally, it's attributes.
2389              
2390             Possible keys in the $options hashref:
2391              
2392             =over 4
2393              
2394             =item o no_attributes => $Boolean
2395              
2396             If 1, the node's attributes are not included in the string returned.
2397              
2398             Default: 0 (include attributes).
2399              
2400             =back
2401              
2402             Calls L.
2403              
2404             Called by L.
2405              
2406             You would not normally call this method.
2407              
2408             If you don't wish to supply options, use format_node({}, $node).
2409              
2410             =head2 generation()
2411              
2412             Returns a list of all nodes (going left-to-right) that are in $node's
2413             generation -- i.e., that are the some number of nodes down from
2414             the root. $root->generation() is just $root.
2415              
2416             Of course, $node is always in its own generation.
2417              
2418             =head2 generation_under($node)
2419              
2420             Like L, but returns only the nodes in $node's generation
2421             that are also descendants of $node -- in other words,
2422              
2423             @us = $node->generation_under( $node->mother->mother );
2424              
2425             is all $node's first cousins (to borrow yet more kinship terminology) --
2426             assuming $node does indeed have a grandmother. Actually "cousins" isn't
2427             quite an apt word, because C<@us> ends up including $node's siblings and
2428             $node.
2429              
2430             Actually, L is just an alias to L, but I
2431             figure that this:
2432              
2433             @us = $node->generation_under($way_upline);
2434              
2435             is a bit more readable than this:
2436              
2437             @us = $node->generation($way_upline);
2438              
2439             But it's up to you.
2440              
2441             $node->generation_under($node) returns just $node.
2442              
2443             If you call $node->generation_under($node) but NODE2 is not $node or an
2444             ancestor of $node, it behaves as if you called just $node->generation().
2445              
2446             =head2 hashref2string($hashref)
2447              
2448             Returns the given hashref as a string.
2449              
2450             Called by L.
2451              
2452             =head2 is_daughter_of($node2)
2453              
2454             Returns true iff $node is a daughter of $node2.
2455             Currently implemented as just a test of ($it->mother eq $node2).
2456              
2457             =head2 is_node()
2458              
2459             This always returns true. More pertinently, $object->can('is_node')
2460             is true (regardless of what L would do if called) for objects
2461             belonging to this class or for any class derived from it.
2462              
2463             =head2 is_root()
2464              
2465             Returns 1 if the caller is the root, and 0 if it is not.
2466              
2467             =head2 leaves_under()
2468              
2469             Returns a list (going left-to-right) of all the leaf nodes under
2470             $node. ("Leaf nodes" are also called "terminal nodes" -- i.e., nodes
2471             that have no daughters.) Returns $node in the degenerate case of
2472             $node being a leaf itself.
2473              
2474             =head2 left_sister()
2475              
2476             Returns the node that's the immediate left sister of $node. If $node
2477             is the leftmost (or only) daughter of its mother (or has no mother),
2478             then this returns undef.
2479              
2480             See also L and L.
2481              
2482             =head2 left_sisters()
2483              
2484             Returns a list of nodes that're sisters to the left of $node. If
2485             $node is the leftmost (or only) daughter of its mother (or has no
2486             mother), then this returns an empty list.
2487              
2488             See also L and L.
2489              
2490             =head2 lol_to_tree($lol)
2491              
2492             This must be called as a class method.
2493              
2494             Converts something like bracket-notation for "Chomsky trees" (or
2495             rather, the closest you can come with Perl
2496             list-of-lists(-of-lists(-of-lists))) into a tree structure. Returns
2497             the root of the tree converted.
2498              
2499             The conversion rules are that: 1) if the last (possibly the only) item
2500             in a given list is a scalar, then that is used as the "name" attribute
2501             for the node based on this list. 2) All other items in the list
2502             represent daughter nodes of the current node -- recursively so, if
2503             they are list references; otherwise, (non-terminal) scalars are
2504             considered to denote nodes with that name. So ['Foo', 'Bar', 'N'] is
2505             an alternate way to represent [['Foo'], ['Bar'], 'N'].
2506              
2507             An example will illustrate:
2508              
2509             use Tree::DAG_Node;
2510             $lol =
2511             [
2512             [
2513             [ [ 'Det:The' ],
2514             [ [ 'dog' ], 'N'], 'NP'],
2515             [ '/with rabies\\', 'PP'],
2516             'NP'
2517             ],
2518             [ 'died', 'VP'],
2519             'S'
2520             ];
2521             $tree = Tree::DAG_Node->lol_to_tree($lol);
2522             $diagram = $tree->draw_ascii_tree;
2523             print map "$_\n", @$diagram;
2524              
2525             ...returns this tree:
2526              
2527             |
2528            
2529             |
2530             /------------------\
2531             | |
2532            
2533             | |
2534             /---------------\
2535             | |
2536            
2537             | |
2538             /-------\
2539             | |
2540            
2541             |
2542            
2543              
2544             By the way (and this rather follows from the above rules), when
2545             denoting a LoL tree consisting of just one node, this:
2546              
2547             $tree = Tree::DAG_Node->lol_to_tree( 'Lonely' );
2548              
2549             is okay, although it'd probably occur to you to denote it only as:
2550              
2551             $tree = Tree::DAG_Node->lol_to_tree( ['Lonely'] );
2552              
2553             which is of course fine, too.
2554              
2555             =head2 mother()
2556              
2557             This returns what node is $node's mother. This is undef if $node has
2558             no mother -- i.e., if it is a root.
2559              
2560             See also L and L.
2561              
2562             =head2 my_daughter_index()
2563              
2564             Returns what index this daughter is, in its mother's C list.
2565             In other words, if $node is ($node->mother->daughters)[3], then
2566             $node->my_daughter_index returns 3.
2567              
2568             As a special case, returns 0 if $node has no mother.
2569              
2570             =head2 name()
2571              
2572             =head2 name(SCALAR)
2573              
2574             In the first form, returns the value of the node object's "name"
2575             attribute. In the second form, sets it to the value of SCALAR.
2576              
2577             =head2 new($hashref)
2578              
2579             These options are supported in $hashref:
2580              
2581             =over 4
2582              
2583             =item o attributes => A hashref of attributes
2584              
2585             =item o daughters => An arrayref of nodes
2586              
2587             =item o mother => A node
2588              
2589             =item o name => A string
2590              
2591             =back
2592              
2593             See also L for a long discussion on object creation.
2594              
2595             =head2 new_daughter()
2596              
2597             =head2 new_daughter($options)
2598              
2599             This B a B node (of the same class as $mother), and
2600             adds it to the (right) end of the daughter list of $mother. This is
2601             essentially the same as going
2602              
2603             $daughter = $mother->new;
2604             $mother->add_daughter($daughter);
2605              
2606             but is rather more efficient because (since $daughter is guaranteed new
2607             and isn't linked to/from anything), it doesn't have to check that
2608             $daughter isn't an ancestor of $mother, isn't already daughter to a
2609             mother it needs to be unlinked from, isn't already in $mother's
2610             daughter list, etc.
2611              
2612             As you'd expect for a constructor, it returns the node-object created.
2613              
2614             Note that if you radically change 'mother'/'daughters' bookkeeping,
2615             you may have to change this routine, since it's one of the places
2616             that directly writes to 'daughters' and 'mother'.
2617              
2618             =head2 new_daughter_left()
2619              
2620             =head2 new_daughter_left($options)
2621              
2622             This is just like $mother->new_daughter, but adds the new daughter
2623             to the left (start) of $mother's daughter list.
2624              
2625             Note that if you radically change 'mother'/'daughters' bookkeeping,
2626             you may have to change this routine, since it's one of the places
2627             that directly writes to 'daughters' and 'mother'.
2628              
2629             =head2 node2string($options, $node, $vert_dashes)
2630              
2631             Returns a string of the node's name and attributes, with a leading indent, suitable for printing.
2632              
2633             Possible keys in the $options hashref:
2634              
2635             =over 4
2636              
2637             =item o no_attributes => $Boolean
2638              
2639             If 1, the node's attributes are not included in the string returned.
2640              
2641             Default: 0 (include attributes).
2642              
2643             =back
2644              
2645             Ignore the parameter $vert_dashes. The code uses it as temporary storage.
2646              
2647             Calls L.
2648              
2649             Called by L.
2650              
2651             =head2 quote_name($name)
2652              
2653             Returns the string "'$name'", which is used in various methods for outputting node names.
2654              
2655             =head2 random_network($options)
2656              
2657             This method can be called as a class method or as an object method.
2658              
2659             In the first case, constructs a randomly arranged network under a new
2660             node, and returns the root node of that tree. In the latter case,
2661             constructs the network under $node.
2662              
2663             Currently, this is implemented a bit half-heartedly, and
2664             half-wittedly. I basically needed to make up random-looking networks
2665             to stress-test the various tree-dumper methods, and so wrote this. If
2666             you actually want to rely on this for any application more
2667             serious than that, I suggest examining the source code and seeing if
2668             this does really what you need (say, in reliability of randomness);
2669             and feel totally free to suggest changes to me (especially in the form
2670             of "I rewrote L, here's the code...")
2671              
2672             It takes four options:
2673              
2674             =over 4
2675              
2676             =item o max_node_count -- maximum number of nodes this tree will be allowed to have (counting the
2677             root)
2678              
2679             Default: 25.
2680              
2681             =item o min_depth -- minimum depth for the tree
2682              
2683             Leaves can be generated only after this depth is reached, so the tree will be at
2684             least this deep -- unless max_node_count is hit first.
2685              
2686             Default: 2.
2687              
2688             =item o max_depth -- maximum depth for the tree
2689              
2690             The tree will not be deeper than this.
2691              
2692             Default: 3 plus min_depth.
2693              
2694             =item o max_children -- maximum number of children any mother in the tree can have.
2695              
2696             Default: 4.
2697              
2698             =back
2699              
2700             =head2 read_attributes($s)
2701              
2702             Parses the string $s and extracts the name and attributes, assuming the format is as generated by
2703             L.
2704              
2705             This bascially means the attribute string was generated by L.
2706              
2707             Attributes may be absent, in which case they default to {}.
2708              
2709             Returns a new node with this name and these attributes.
2710              
2711             This method is for use by L.
2712              
2713             See t/tree.without.attributes.txt and t/tree.with.attributes.txt for sample data.
2714              
2715             =head2 read_tree($file_name)
2716              
2717             Returns the root of the tree read from $file_name.
2718              
2719             The file must have been written by re-directing the output of
2720             L to a file, since it makes assumptions about the format
2721             of the stringified attributes.
2722              
2723             read_tree() works with utf-8 data. See t/read.tree.t and t/tree.utf8.attributes.txt.
2724              
2725             Note: To call this method you need a caller. It'll be a tree of 1 node. The reason is that inside
2726             this method it calls various other methods, and for these calls it needs $self. That way, those
2727             methods can be called from anywhere, and not just from within read_tree().
2728              
2729             For reading and writing trees to databases, see L.
2730              
2731             Calls L.
2732              
2733             =head2 remove_daughter(LIST)
2734              
2735             An exact synonym for L.
2736              
2737             =head2 remove_daughters(LIST)
2738              
2739             This removes the nodes listed in LIST from $mother's daughter list.
2740             This is a no-operation if LIST is empty. If there are things in LIST
2741             that aren't a current daughter of $mother, they are ignored.
2742              
2743             Not to be confused with L.
2744              
2745             =head2 replace_with(LIST)
2746              
2747             This replaces $node in its mother's daughter list, by unlinking $node
2748             and replacing it with the items in LIST. This returns a list consisting
2749             of $node followed by LIST, i.e., the nodes that replaced it.
2750              
2751             LIST can include $node itself (presumably at most once). LIST can
2752             also be the empty list. However, if any items in LIST are sisters to
2753             $node, they are ignored, and are not in the copy of LIST passed as the
2754             return value.
2755              
2756             As you might expect for any linking operation, the items in LIST
2757             cannot be $node's mother, or any ancestor to it; and items in LIST are,
2758             of course, unlinked from their mothers (if they have any) as they're
2759             linked to $node's mother.
2760              
2761             (In the special (and bizarre) case where $node is root, this simply calls
2762             $this->unlink_from_mother on all the items in LIST, making them roots of
2763             their own trees.)
2764              
2765             Note that the daughter-list of $node is not necessarily affected; nor
2766             are the daughter-lists of the items in LIST. I mention this in case you
2767             think replace_with switches one node for another, with respect to its
2768             mother list B its daughter list, leaving the rest of the tree
2769             unchanged. If that's what you want, replacing $Old with $New, then you
2770             want:
2771              
2772             $New->set_daughters($Old->clear_daughters);
2773             $Old->replace_with($New);
2774              
2775             (I can't say $node's and LIST-items' daughter lists are B
2776             affected my replace_with -- they can be affected in this case:
2777              
2778             $N1 = ($node->daughters)[0]; # first daughter of $node
2779             $N2 = ($N1->daughters)[0]; # first daughter of $N1;
2780             $N3 = Tree::DAG_Node->random_network; # or whatever
2781             $node->replace_with($N1, $N2, $N3);
2782              
2783             As a side affect of attaching $N1 and $N2 to $node's mother, they're
2784             unlinked from their parents ($node, and $N1, respectively).
2785             But N3's daughter list is unaffected.
2786              
2787             In other words, this method does what it has to, as you'd expect it
2788             to.
2789              
2790             =head2 replace_with_daughters()
2791              
2792             This replaces $node in its mother's daughter list, by unlinking $node
2793             and replacing it with its daughters. In other words, $node becomes
2794             motherless and daughterless as its daughters move up and take its place.
2795             This returns a list consisting of $node followed by the nodes that were
2796             its daughters.
2797              
2798             In the special (and bizarre) case where $node is root, this simply
2799             unlinks its daughters from it, making them roots of their own trees.
2800              
2801             Effectively the same as $node->replace_with($node->daughters), but more
2802             efficient, since less checking has to be done. (And I also think
2803             $node->replace_with_daughters is a more common operation in
2804             tree-wrangling than $node->replace_with(LIST), so deserves a named
2805             method of its own, but that's just me.)
2806              
2807             Note that if you radically change 'mother'/'daughters' bookkeeping,
2808             you may have to change this routine, since it's one of the places
2809             that directly writes to 'daughters' and 'mother'.
2810              
2811             =head2 right_sister()
2812              
2813             Returns the node that's the immediate right sister of $node. If $node
2814             is the rightmost (or only) daughter of its mother (or has no mother),
2815             then this returns undef.
2816              
2817             See also L and L.
2818              
2819             =head2 right_sisters()
2820              
2821             Returns a list of nodes that're sisters to the right of $node. If
2822             $node is the rightmost (or only) daughter of its mother (or has no
2823             mother), then this returns an empty list.
2824              
2825             See also L and L.
2826              
2827             =head2 root()
2828              
2829             Returns the root of whatever tree $node is a member of. If $node is
2830             the root, then the result is $node itself.
2831              
2832             Not to be confused with L.
2833              
2834             =head2 self_and_descendants()
2835              
2836             Returns a list consisting of itself (as element 0) and all the
2837             descendants of $node. Returns just itself if $node is a
2838             terminal_node.
2839              
2840             (Note that it's spelled "descendants", not "descendents".)
2841              
2842             =head2 self_and_sisters()
2843              
2844             Returns a list of all nodes (going left-to-right) that have the same
2845             mother as $node -- including $node itself. This is just like
2846             $node->mother->daughters, except that that fails where $node is root,
2847             whereas $root->self_and_siblings, as a special case, returns $root.
2848              
2849             (Contrary to how you may interpret how this method is named, "self" is
2850             not (necessarily) the first element of what's returned.)
2851              
2852             =head2 set_daughters(LIST)
2853              
2854             This unlinks all $mother's daughters, and replaces them with the
2855             daughters in LIST.
2856              
2857             Currently implemented as just $mother->clear_daughters followed by
2858             $mother->add_daughters(LIST).
2859              
2860             =head2 simple_lol_to_tree($simple_lol)
2861              
2862             This must be called as a class method.
2863              
2864             This is like lol_to_tree, except that rule 1 doesn't apply -- i.e.,
2865             all scalars (or really, anything not a listref) in the LoL-structure
2866             end up as named terminal nodes, and only terminal nodes get names
2867             (and, of course, that name comes from that scalar value). This method
2868             is useful for making things like expression trees, or at least
2869             starting them off. Consider that this:
2870              
2871             $tree = Tree::DAG_Node->simple_lol_to_tree(
2872             [ 'foo', ['bar', ['baz'], 'quux'], 'zaz', 'pati' ]
2873             );
2874              
2875             converts from something like a Lispish or Iconish tree, if you pretend
2876             the brackets are parentheses.
2877              
2878             Note that there is a (possibly surprising) degenerate case of what I'm
2879             calling a "simple-LoL", and it's like this:
2880              
2881             $tree = Tree::DAG_Node->simple_lol_to_tree('Lonely');
2882              
2883             This is the (only) way you can specify a tree consisting of only a
2884             single node, which here gets the name 'Lonely'.
2885              
2886             =head2 sisters()
2887              
2888             Returns a list of all nodes (going left-to-right) that have the same
2889             mother as $node -- B $node itself. If $node is root,
2890             this returns empty-list.
2891              
2892             =head2 string2hashref($s)
2893              
2894             Returns the hashref built from the string.
2895              
2896             The string is expected to be something like
2897             '{AutoCommit => '1', PrintError => "0", ReportError => 1}'.
2898              
2899             The empty string is returned as {}.
2900              
2901             Called by L.
2902              
2903             =head2 tree_to_lol()
2904              
2905             Returns that tree (starting at $node) represented as a LoL, like what
2906             $lol, above, holds. (This is as opposed to L,
2907             which returns the viewable code like what gets evaluated and stored in
2908             $lol, above.)
2909              
2910             Undefined node names are returned as the string 'undef'.
2911              
2912             See also L.
2913              
2914             Lord only knows what you use this for -- maybe for feeding to
2915             Data::Dumper, in case L doesn't do just what you
2916             want?
2917              
2918             =head2 tree_to_lol_notation($options)
2919              
2920             Dumps a tree (starting at $node) as the sort of LoL-like bracket
2921             notation you see in the above example code. Returns just one big
2922             block of text. The only option is "multiline" -- if true, it dumps
2923             the text as the sort of indented structure as seen above; if false
2924             (and it defaults to false), dumps it all on one line (with no
2925             indenting, of course).
2926              
2927             For example, starting with the tree from the above example,
2928             this:
2929              
2930             print $tree->tree_to_lol_notation, "\n";
2931              
2932             prints the following (which I've broken over two lines for sake of
2933             printability of documentation):
2934              
2935             [[[['Det:The'], [['dog'], 'N'], 'NP'], [["/with rabies\x5c"],
2936             'PP'], 'NP'], [['died'], 'VP'], 'S'],
2937              
2938             Doing this:
2939              
2940             print $tree->tree_to_lol_notation({ multiline => 1 });
2941              
2942             prints the same content, just spread over many lines, and prettily
2943             indented.
2944              
2945             Undefined node names are returned as the string 'undef'.
2946              
2947             =head2 tree_to_simple_lol()
2948              
2949             Returns that tree (starting at $node) represented as a simple-LoL --
2950             i.e., one where non-terminal nodes are represented as listrefs, and
2951             terminal nodes are gotten from the contents of those nodes' "name'
2952             attributes.
2953              
2954             Note that in the case of $node being terminal, what you get back is
2955             the same as $node->name.
2956              
2957             Compare to tree_to_simple_lol_notation.
2958              
2959             Undefined node names are returned as the string 'undef'.
2960              
2961             See also L.
2962              
2963             =head2 tree_to_simple_lol_notation($options)
2964              
2965             A simple-LoL version of tree_to_lol_notation (which see); takes the
2966             same options.
2967              
2968             Undefined node names are returned as the string 'undef'.
2969              
2970             =head2 tree2string($options, [$some_tree])
2971              
2972             Here, the [] represent an optional parameter.
2973              
2974             Returns an arrayref of lines, suitable for printing.
2975              
2976             Draws a nice ASCII-art representation of the tree structure.
2977              
2978             The tree looks like:
2979              
2980             Root. Attributes: {}
2981             |--- Â. Attributes: {# => "ÂÂ"}
2982             | |--- â. Attributes: {# => "ââ"}
2983             | | |--- É. Attributes: {# => "ÉÉ"}
2984             | |--- ä. Attributes: {# => "ää"}
2985             | |--- é. Attributes: {# => "éé"}
2986             | |--- Ñ. Attributes: {# => "ÑÑ"}
2987             | |--- ñ. Attributes: {# => "ññ"}
2988             | |--- Ô. Attributes: {# => "ÔÔ"}
2989             | |--- ô. Attributes: {# => "ôô"}
2990             | |--- ô. Attributes: {# => "ôô"}
2991             |--- ß. Attributes: {# => "ßß"}
2992             |--- ®. Attributes: {# => "®®"}
2993             | |--- ©. Attributes: {# => "©©"}
2994             |--- £. Attributes: {# => "££"}
2995             |--- €. Attributes: {# => "€€"}
2996             |--- √. Attributes: {# => "√√"}
2997             |--- ×xX. Attributes: {# => "×xX×xX"}
2998             |--- í. Attributes: {# => "íí"}
2999             |--- ú. Attributes: {# => "úú"}
3000             |--- «. Attributes: {# => "««"}
3001             |--- ». Attributes: {# => "»»"}
3002              
3003             Or, without attributes:
3004              
3005             Root
3006             |--- Â
3007             | |--- â
3008             | | |--- É
3009             | |--- ä
3010             | |--- é
3011             | |--- Ñ
3012             | |--- ñ
3013             | |--- Ô
3014             | |--- ô
3015             | |--- ô
3016             |--- ß
3017             |--- ®
3018             | |--- ©
3019             |--- £
3020             |--- €
3021             |--- √
3022             |--- ×xX
3023             |--- í
3024             |--- ú
3025             |--- «
3026             |--- »
3027              
3028             See scripts/cut.and.paste.subtrees.pl.
3029              
3030             Example usage:
3031              
3032             print map("$_\n", @{$tree->tree2string});
3033              
3034             Can be called with $some_tree set to any $node, and will print the tree assuming $node is the root.
3035              
3036             If you don't wish to supply options, use tree2string({}, $node).
3037              
3038             Possible keys in the $options hashref (which defaults to {}):
3039              
3040             =over 4
3041              
3042             =item o no_attributes => $Boolean
3043              
3044             If 1, the node's attributes are not included in the string returned.
3045              
3046             Default: 0 (include attributes).
3047              
3048             =back
3049              
3050             Calls L.
3051              
3052             See also L.
3053              
3054             =head2 unlink_from_mother()
3055              
3056             This removes node from the daughter list of its mother. If it has no
3057             mother, this is a no-operation.
3058              
3059             Returns the mother unlinked from (if any).
3060              
3061             =head2 walk_down($options)
3062              
3063             Performs a depth-first traversal of the structure at and under $node.
3064             What it does at each node depends on the value of the options hashref,
3065             which you must provide. There are three options, "callback" and
3066             "callbackback" (at least one of which must be defined, as a sub
3067             reference), and "_depth".
3068              
3069             This is what I does, in pseudocode form:
3070              
3071             =over 4
3072              
3073             =item o Starting point
3074              
3075             Start at the $node given.
3076              
3077             =item o Callback
3078              
3079             If there's a I, call it with $node as the first argument,
3080             and the options hashref as the second argument (which contains the
3081             potentially useful I<_depth>, remember). This function must return
3082             true or false -- if false, it will block the next step:
3083              
3084             =item o Daughters
3085              
3086             If $node has any daughter nodes, increment I<_depth>, and call
3087             $daughter->walk_down($options) for each daughter (in order, of
3088             course), where options_hashref is the same hashref it was called with.
3089             When this returns, decrements I<_depth>.
3090              
3091             =item Callbackback
3092              
3093             If there's a I, call just it as with I (but
3094             tossing out the return value). Note that I returning false
3095             blocks traversal below $node, but doesn't block calling callbackback
3096             for $node. (Incidentally, in the unlikely case that $node has stopped
3097             being a node object, I won't get called.)
3098              
3099             =item o Return
3100              
3101             =back
3102              
3103             $node->walk_down($options) is the way to recursively do things to a tree (if you
3104             start at the root) or part of a tree; if what you're doing is best done
3105             via pre-pre order traversal, use I; if what you're doing is
3106             best done with post-order traversal, use I.
3107             I is even the basis for plenty of the methods in this
3108             class. See the source code for examples both simple and horrific.
3109              
3110             Note that if you don't specify I<_depth>, it effectively defaults to
3111             0. You should set it to scalar($node->ancestors) if you want
3112             I<_depth> to reflect the true depth-in-the-tree for the nodes called,
3113             instead of just the depth below $node. (If $node is the root, there's
3114             no difference, of course.)
3115              
3116             And B, it's a bad idea to modify the tree from the callback.
3117             Unpredictable things may happen. I instead suggest having your callback
3118             add to a stack of things that need changing, and then, once I
3119             is all finished, changing those nodes from that stack.
3120              
3121             Note that the existence of I doesn't mean you can't write
3122             you own special-use traversers.
3123              
3124             =head1 WHEN AND HOW TO DESTROY THE TREE
3125              
3126             It should be clear to you that if you've built a big parse tree or
3127             something, and then you're finished with it, you should call
3128             $some_node->delete_tree on it if you want the memory back.
3129              
3130             But consider this case: you've got this tree:
3131              
3132             A
3133             / | \
3134             B C D
3135             | | \
3136             E X Y
3137              
3138             Let's say you decide you don't want D or any of its descendants in the
3139             tree, so you call D->unlink_from_mother. This does NOT automagically
3140             destroy the tree D-X-Y. Instead it merely splits the tree into two:
3141              
3142             A D
3143             / \ / \
3144             B C X Y
3145             |
3146             E
3147              
3148             To destroy D and its little tree, you have to explicitly call
3149             delete_tree on it.
3150              
3151             Note, however, that if you call C->unlink_from_mother, and if you don't
3152             have a link to C anywhere, then it B magically go away. This is
3153             because nothing links to C -- whereas with the D-X-Y tree, D links to
3154             X and Y, and X and Y each link back to D. Note that calling
3155             C->delete_tree is harmless -- after all, a tree of only one node is
3156             still a tree.
3157              
3158             So, this is a surefire way of getting rid of all $node's children and
3159             freeing up the memory associated with them and their descendants:
3160              
3161             foreach my $it ($node->clear_daughters) { $it->delete_tree }
3162              
3163             Just be sure not to do this:
3164              
3165             foreach my $it ($node->daughters) { $it->delete_tree }
3166             $node->clear_daughters;
3167              
3168             That's bad; the first call to $_->delete_tree will climb to the root
3169             of $node's tree, and nuke the whole tree, not just the bits under $node.
3170             You might as well have just called $node->delete_tree.
3171             (Moreavor, once $node is dead, you can't call clear_daughters on it,
3172             so you'll get an error there.)
3173              
3174             =head1 BUG REPORTS
3175              
3176             If you find a bug in this library, report it to me as soon as possible,
3177             at the address listed in the MAINTAINER section, below. Please try to
3178             be as specific as possible about how you got the bug to occur.
3179              
3180             =head1 HELP!
3181              
3182             If you develop a given routine for dealing with trees in some way, and
3183             use it a lot, then if you think it'd be of use to anyone else, do email
3184             me about it; it might be helpful to others to include that routine, or
3185             something based on it, in a later version of this module.
3186              
3187             It's occurred to me that you might like to (and might yourself develop
3188             routines to) draw trees in something other than ASCII art. If you do so
3189             -- say, for PostScript output, or for output interpretable by some
3190             external plotting program -- I'd be most interested in the results.
3191              
3192             =head1 RAMBLINGS
3193              
3194             This module uses "strict", but I never wrote it with -w warnings in
3195             mind -- so if you use -w, do not be surprised if you see complaints
3196             from the guts of DAG_Node. As long as there is no way to turn off -w
3197             for a given module (instead of having to do it in every single
3198             subroutine with a "local $^W"), I'm not going to change this. However,
3199             I do, at points, get bursts of ambition, and I try to fix code in
3200             DAG_Node that generates warnings, I -- which is
3201             only occasionally. Feel free to email me any patches for any such
3202             fixes you come up with, tho.
3203              
3204             Currently I don't assume (or enforce) anything about the class
3205             membership of nodes being manipulated, other than by testing whether
3206             each one provides a method L, a la:
3207              
3208             die "Not a node!!!" unless UNIVERSAL::can($node, "is_node");
3209              
3210             So, as far as I'm concerned, a given tree's nodes are free to belong to
3211             different classes, just so long as they provide/inherit L, the
3212             few methods that this class relies on to navigate the tree, and have the
3213             same internal object structure, or a superset of it. Presumably this
3214             would be the case for any object belonging to a class derived from
3215             C, or belonging to C itself.
3216              
3217             When routines in this class access a node's "mother" attribute, or its
3218             "daughters" attribute, they (generally) do so directly (via
3219             $node->{'mother'}, etc.), for sake of efficiency. But classes derived
3220             from this class should probably do this instead thru a method (via
3221             $node->mother, etc.), for sake of portability, abstraction, and general
3222             goodness.
3223              
3224             However, no routines in this class (aside from, necessarily, I<_init()>,
3225             I<_init_name()>, and L) access the "name" attribute directly;
3226             routines (like the various tree draw/dump methods) get the "name" value
3227             thru a call to $obj->name(). So if you want the object's name to not be
3228             a real attribute, but instead have it derived dynamically from some feature
3229             of the object (say, based on some of its other attributes, or based on
3230             its address), you can to override the L method, without causing
3231             problems. (Be sure to consider the case of $obj->name as a write
3232             method, as it's used in I and L.)
3233              
3234             =head1 FAQ
3235              
3236             =head2 Which is the best tree processing module?
3237              
3238             C, as it happens. More details: L.
3239              
3240             =head2 How to process every node in tree?
3241              
3242             See L. $options normally looks like this, assuming we wish to pass in
3243             an arrayref as a stack:
3244              
3245             my(@stack);
3246              
3247             $tree -> walk_down
3248             ({
3249             callback =>
3250             sub
3251             {
3252             my(@node, $options) = @_;
3253              
3254             # Process $node, using $options...
3255              
3256             push @{$$options{stack} }, $node -> name;
3257              
3258             return 1; # Keep walking.
3259             },
3260             _depth => 0,
3261             stack => \@stack,
3262             });
3263              
3264             # Process @stack...
3265              
3266             =head2 How do I switch from Tree to Tree::DAG_Node?
3267              
3268             =over 4
3269              
3270             =item o The node's name
3271              
3272             In C you use $node -> value and in C it's $node -> name.
3273              
3274             =item o The node's attributes
3275              
3276             In C you use $node -> meta and in C it's $node -> attributes.
3277              
3278             =back
3279              
3280             =head2 Are there techniques for processing lists of nodes?
3281              
3282             =over 4
3283              
3284             =item o Copy the daughter list, and change it
3285              
3286             @them = $mother->daughters;
3287             @removed = splice(@them, 0, 2, @new_nodes);
3288              
3289             $mother->set_daughters(@them);
3290              
3291             =item o Select a sub-set of nodes
3292              
3293             $mother->set_daughters
3294             (
3295             grep($_->name =~ /wanted/, $mother->daughters)
3296             );
3297              
3298             =back
3299              
3300             =head2 Why did you break up the sections of methods in the POD?
3301              
3302             Because I want to list the methods in alphabetical order.
3303              
3304             =head2 Why did you move the POD to the end?
3305              
3306             Because the apostrophes in the text confused the syntax hightlighter in my editor UltraEdit.
3307              
3308             =head1 SEE ALSO
3309              
3310             =over 4
3311              
3312             =item o L, L and L
3313              
3314             Sean is also the author of these modules.
3315              
3316             =item o L
3317              
3318             Lightweight.
3319              
3320             =item o L
3321              
3322             Lightweight.
3323              
3324             =item o L
3325              
3326             Lightweight.
3327              
3328             =item o L
3329              
3330             Lightweight.
3331              
3332             =item o L
3333              
3334             Uses L.
3335              
3336             =back
3337              
3338             C itself is also lightweight.
3339              
3340             =head1 REFERENCES
3341              
3342             Wirth, Niklaus. 1976. I
3343             Prentice-Hall, Englewood Cliffs, NJ.
3344              
3345             Knuth, Donald Ervin. 1997. I
3346             Third Edition: Fundamental Algorithms>. Addison-Wesley, Reading, MA.
3347              
3348             Wirth's classic, currently and lamentably out of print, has a good
3349             section on trees. I find it clearer than Knuth's (if not quite as
3350             encyclopedic), probably because Wirth's example code is in a
3351             block-structured high-level language (basically Pascal), instead
3352             of in assembler (MIX).
3353              
3354             Until some kind publisher brings out a new printing of Wirth's book,
3355             try poking around used bookstores (or C) for a copy.
3356             I think it was also republished in the 1980s under the title
3357             I, and in a German edition called
3358             I. (That is, I'm sure books by Knuth
3359             were published under those titles, but I'm I that they're just
3360             later printings/editions of I
3361             Programs>.)
3362              
3363             =head1 MACHINE-READABLE CHANGE LOG
3364              
3365             The file Changes was converted into Changelog.ini by L.
3366              
3367             =head1 REPOSITORY
3368              
3369             L
3370              
3371             =head1 SUPPORT
3372              
3373             Email the author, or log a bug on RT:
3374              
3375             L.
3376              
3377             =head1 ACKNOWLEDGEMENTS
3378              
3379             The code to print the tree, in tree2string(), was adapted from
3380             L by the dread Stevan Little.
3381              
3382             =head1 MAINTAINER
3383              
3384             David Hand, C<< >> up to V 1.06.
3385              
3386             Ron Savage C<< >> from V 1.07.
3387              
3388             In this POD, usage of 'I' refers to Sean, up until V 1.07.
3389              
3390             =head1 AUTHOR
3391              
3392             Sean M. Burke, C<< >>
3393              
3394             =head1 COPYRIGHT, LICENSE, AND DISCLAIMER
3395              
3396             Copyright 1998-2001, 2004, 2007 by Sean M. Burke and David Hand.
3397              
3398             This Program of ours is 'OSI Certified Open Source Software';
3399             you can redistribute it and/or modify it under the terms of
3400             The Perl License, a copy of which is available at:
3401             http://dev.perl.org/licenses/
3402              
3403             This program is distributed in the hope that it will be useful, but
3404             without any warranty; without even the implied warranty of
3405             merchantability or fitness for a particular purpose.
3406              
3407             =cut