in reply to Re: Q on HTML::Element recursive lambda comment
in thread Q on HTML::Element recursive lambda comment

Okay, duh, thanks.

Another question though; here's why I often use the "anonymous lambda" style (dynamic sub): if I do something like this (embedded sub):

sub traverse { my $start_node = HTML::TreeBuilder->new; $start_node->parse_file(shift); { my $counter = 'x0000'; sub give_id { my $x = $_[0]; $x->attr('id', $counter++) unless defined $x->attr('id'); foreach my $c ($x->content_list) { give_id($c) if ref $c; # ignore text nodes } }; give_id($start_node); } }
The var $counter is captured in the closure and does not get reset even though I'd like it to be reset. It's either this way and moving and resetting $counter by hand outside the block (which I won't do because it's logically inside the function and also easy to forget) or using the dynamic sub and risk a memory leak - how would I get the best of both worlds (uncaptured var + no risk of memory leak). Using a private embedded package or putting everything in it's own package seems wordy.

Thanks for the enlightenment.

Replies are listed 'Best First'.
Re: Re: Re: Q on HTML::Element recursive lambda comment
by fizbin (Chaplain) on Mar 08, 2004 at 20:24 UTC
    Well, I'd do it by leaving in the undef statement. Either that, or replace it with something commented:
    { ... $give_id->($start_node); $give_id = 0; # Break circular structure and avoid memory leak }
    That is, just make sure to set $give_id to some value that doesn't depend on $give_id before $give_id goes out of scope.