in reply to Basic mod-perl question : why my variable is undefined ?

Are you using warnings? Have you checked your logs? If you are getting a warning like

Variable "$lig" will not stay shared
You have scoping problems with your closure. That warning will be issued by code like
sub one { my $x; sub two { print $x; } }

Since mod_perl compiles all your scripts into a dispatch table (as I understand it), it seems plausible to me that the copy of $lig referenced in your compiled copy of xxx() is not the lexically-scoped variable you are working with after your script executes a couple times.


#11929 First ask yourself `How would I do this without a computer?' Then have the computer do it the same way.

Replies are listed 'Best First'.
Re^2: Basic mod-perl question : why my variable is undefined ?
by pcouderc (Monk) on Jul 23, 2014 at 15:47 UTC
    Yes you are right, "I" am exactly in this case, as mod_perl includes (automatically) my full script in a sub. So maybe it is my understanding of what is a "closure" or what is "lexically-scoped" which is bad.
    I would have thought that as $x is defined in sub one, its scope goes until the end of sub one. I suppose I am wrong..? Why ? And is there a way to have a variable common to one and two, but declared inside one, as with mod_perl I have no access (at my knowledge) outside one... ?
      The problem with the demo code is that each subroutine is only compiled once. That means that the $x variable in two corresponds to the $x variable in the first call of one. The first instance of $x persists as there is a reference to it stored in two.

      Solutions include explicitly passing the value, forcing recompile each time through using a code reference (sub), swapping $x to a constant... What is the reason you aren't just passing in the value of $lig?


      #11929 First ask yourself `How would I do this without a computer?' Then have the computer do it the same way.

        OK, I understand. Yes, in this simple case, it will be the solution. But it is very complicated if you must pass all the variable without the possiblity to have common data. It becomes more complicated than a good old C program... I you add the mass of problems linked to UTF8, I ask me if PERL is still a good solution.... Shhht!