A Real Use for Closures

| No Comments

I think I read about closures first a few years ago in the Camel book (first edition). At the time they seemed to be a neat toy, but not something I would ever need. Now, I've finally come across a scenario where closures provide the best solution.

I'm using XML::Parser (no doubt that's old school but I need something that's solid and portable). With that, I get to define a bunch of callbacks. I want the callbacks to be methods in an object I've created. Problem: XML::Parser wants references to subroutines, not objects. Solution: pass references to anonymous subroutines created on the spot. There's a $self reference in lexical scope, so I can just refer to that in the anonymous subroutine. Thanks to the magic of closures, it's available, even when the sub is being called back later.

    my $parser = new XML::Parser(ErrorContext => 2);
    $parser->setHandlers(
        Start => sub { $self->handle_start(@_) },
        Char  => sub { $self->handle_characters(@_) },
        End   => sub { $self->handle_end(@_) }
    );

I find this surprisingly readable. Even if I didn't know about closures, I would be able to read and understand this code: DWIM at its best. (By the way, syntactic closures seem to have been invented as recently as 1988.)

About this Entry

This page contains a single entry by Christian published on April 26, 2005 4:43 PM.

Tiny Patch for Text::CSV was the previous entry in this blog.

Least Helpful Error Message Ever is the next entry in this blog.

Find recent content on the main index or look in the archive to find all content.