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

First of all, Sean Burke writes eclectic prose and doesn't write code so much as play with code. I love his style :)

In this bit of the doc, he is rewriting the simple code traversal routine

{ 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); }
to be more lispish. In particular, he is assigning an anonymous sub to a lexical, rather than just creating a give_id sub. Doing the former promotes the sub to a first class object, i.e., it can be assigned to a variable and passed around the same as any other object.

Now, you would expect, $giv_id to go out of scope at the end of the block, but it is used in the anonymous sub, so this 'closure' lives on unless you destroy it explicitly. This may or may not be what you want to do, depending on the rest of your code.

I think the code is perfectly fine to use. It is not very nutty and should pose no problems. But the non-lispy code is a little simpler.

-Mark

Replies are listed 'Best First'.
Re: Re: Q on HTML::Element recursive lambda comment
by flyingmoose (Priest) on Mar 08, 2004 at 19:55 UTC

    Note: I'm (as usual) off-topic...

    I really like it when languages allow me to be lispy -- even though I really dislike being lispy in lisp! Lots of insignificant parenthesis -- Go figure! I'd say this ability of Perl (to allow funky functional constructs without the painful restrictions of pure-functional languages) is 70% of my love of the language. (CPAN and the data structure support fill the other 30%).

    I don't know how many times I've wanted to do something with lamba functions and closures in C, and then I kick myself -- doh -- you can't do that! Java does a little better with the anonymous inner classes, but the syntax is horribly cludgy so I can't give it any browny points. I have this one build engine I'm rather proud of that heavily abuses map and anonymous subs. Why? Well, to keep people from messing with my build system -- err, no, because it's insanely powerful. It is, however, amazing how many self-proclaimed OO Gods can't grok functional code. I like it!

    Back on topic: "Left for an exercise for the reader" is bad form, IMHO, in official documentation or a reference manual. It's fine for a student textbook, but it annoys me to no end when a writer thinks they are clever and then won't explain why they think they are clever. Hey, I'm stupid...sometimes I can't figure out the darn exercises! Teach me, or better, give hints.