in reply to Re^3: Perl to Ruby translator?
in thread Perl to Ruby translator?

People often don't realize that this is a closure:

my $q = CGI->new() sub foo { my $thing = $q->param('thing'); }
Then they try to use it in a persistent environment like mod_perl or FastCGI and they get screwed. I see this happen all the time.

Replies are listed 'Best First'.
Re: Re: Re^3: Perl to Ruby translator?
by BUU (Prior) on Oct 10, 2003 at 19:40 UTC
    For at least my own education, if no one elses, how exactly is that a closure and why are people getting screwed doing it? It seems fairly simple to me..
      It's a closure because the sub foo refers to $q, which is a lexical variable delcared in the enclosing scope. Now, for the rest of the life of this Perl interpreter, the $q inside of the foo subroutine will always have the same value it did the first time this code was run, no matter what you do in the main part of this program. That means you will get crazy results where CGI.pm appears to be caching data from previous requests.
        I was going to tell you why it's not a closure, but fortunately I checked first, and of course, you are right.

        I doubt your central assertion that this sort of thing happens all the time though. How many times do you see named subroutines declared inside loops? Almost never. And I have never heard of anyone accidentally creating a closure.

        Personally, I find using closures a liberating experience, and since they make some hard things easy, actually reduce bugs.

      It's a closure because it contains a reference to a lexical variable ($q) from a parent scope. It could cause problems if later you reassigned $q and thought it would change inside the sub, or thought it go away after the scope of $q ended.

      kelan


      Perl6 Grammar Student