package bin_tree; #create a new instance of the bin_tree object, taking #$depth as an ar +gument... Create a binary tree, #recursively calling new() in order to create a node with #the desired + depth. sub new{ $class=shift; $depth=shift; #pull the class values and the depth beneath the nod +e desired, 0 for no lower nodes $self={value,a,b}; #make our object as an anonymous hash with keyw +ords but no values yet, that way the a and b keys (our branches) defa +ult evaluate to null $self->{value}=0; print $self->{value},"\n"; #just a debugging statement to try to f +igure out whats going on while ($depth >= 1){ #if we need to get deep, recursively call the + new() method, assigning the created objects to our a and b branches $depth--; $self->{a} = bin_tree->new($depth); #problem is here... the ne +w binary tree node never gets returned $self->{b} = bin_tree->new($depth); print $self->{a},"\n"; #debugging statement, this still evalua +tes to null, even though it should be set as an object reference now } bless $self, $class; #make object return $self; #return object } #5 minute depth test function, recursively runs down the "a" side of a + binary tree, returns the depth eventually sub depth_test{ $self=shift; print $i++,"\n"; if (defined $self->{a}){ $depth=$self->{a}->depth_test(); } return $depth+1; } #try to create a three node deep binary tree $bintree = bin_tree->new(3); print "Before:",$bintree->{a},"\n"; $deep = $bintree->depth_test(); print "Depth:",$deep,"\n"; #prove that new() call is just creating the + first level node) $bintree->{a} = bin_tree->new(); $bintree->{a}->{a} = bin_tree->new(); print "After:",$bintree->{a},"\n"; $deep = $bintree->depth_test(); print "Depth:",$deep,"\n"; #prove that when the code is outside of the + object methods, i can use my technique to build a tree
In reply to recursive creation of attached objects? by Anonymous Monk
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |