in reply to Re: Recursion, tree parsing.
in thread Recursion, tree parsing.

You can probably get away without checking for the existance of @{$t->{children}}.

Eh, yer probably right.

But why would I want to do:
change: if(@{$t->{children}}){ with if($#{$t->{children}} > 0){
?

Replies are listed 'Best First'.
Re: Re: Re: Recursion, tree parsing.
by demerphq (Chancellor) on Apr 15, 2003 at 07:38 UTC

    why would I want to do

    You wouldn't. :-) I _think_ the issue the OP was refering to (but actually doesnt deal with) is the possibility that children is undef. Since the dereference is a fetch it wont be automagically created and the if ( @{...} ) will choke. Personally I would replace it and the for with the following

    for my $child ( @{ $t->{children} || [] } ) { }

    Normally I dont put so much whitespace in my expressions, but I figured here it makes things clearer, When dereferencing, if $t->{children} is false then we use an empty anonymous array to iterate over. We dont have to check if there are elements, because if there are, we _will_ iterate over them, and if there are, well, we _wont_.

    BTW, Its a good idea to become quite familiar with binary trees before you play with n-ary trees. It helps to solidy the concepts. A good learning exercise is to implement a Tie::Hash using a binary tree. (Say a sorted hash implemented using a binary tree?) Incidentally any tree structure can be represented using binary trees if necessary so it pays off to understand them well.

    HTH


    ---
    demerphq

    <Elian> And I do take a kind of perverse pleasure in having an OO assembly language...