in reply to Re^3: Catching closures
in thread Catching closures

I'm concerned about things like putting the Apache::Request object into a closure, and getting issues like this : Calls to Apache::Request's param method sometimes end the program and return no data.

And generally, if any other variables persist from request to request just because I used them in a closure, that would be annoying. (Of course, sometimes I want things to persist, and closures are helpful, but I don't do that in the context of calling a method for doing a database transaction).

e.g. I wanted to avoid doing this :
my $object; do_transaction(code => sub {....$object->update..})

On second though, maybe the above is okay, since once the anonymous sub goes away, the reference to $object does too, so maybe I'm being unnecessarily cautious.

Replies are listed 'Best First'.
Re^5: Catching closures
by Joost (Canon) on Mar 06, 2008 at 00:15 UTC
    Whether that code is OK all depends on what happens to $object.

    Note that potential problems with persistent data in mod_perl aren't limited to closures. All kinds of bugs can creep in if you're not taking the persistent nature of mod_perl into account. If you've done mostly CGI programming it can take a while to get comfortable with that, but it's really not much different from writing any other persistent program.

    Detecting unintended closures may be a good thing, but I suggest you just use it in development and turn it off in production and in situations where you may actually want to use closures. That way you can write and test with all kinds of (inefficient) hand holding, and run the code with good performance when it's tested.

    In any case, it's useful to have a good understanding of closures, firstly just because they're a very powerful tool, and secondly because if you know how closures work you're not very likely to make the kinds of mistakes you're detecting here.

      Thanks for the suggestions. This is a situation where it's easy to accidentally create a closure, and rare to have a legitimate use (if there is a legitimate subroutine that uses a closure, it could just be put into a named subroutine, and an anonymous one that's passed to do_transaction could call the named one), so at least a warning on the dev server would be useful. Having used mod_perl for a while, I've seen that accidental closures can be hard to track down, whether they were written by me or someone else on the project.