On Sun, Jan 02, 2000 at 01:13:26PM -0800, Aaron Turner wrote:
> 
> This is driving me nuts.  This code works the first few exectutions, but
> then doesn't after a while.  It's pretty simple, it should print out:
> 
> Name = value1
> Name = value2
> 
> then after a few reloads it prints:
> 
> Name = value1
> Name = value1
> 
> I'm sure it's something stupid, but my brain is apparently fried.

This is a FAQ.  You're declaring a closure by using %variable in that
inside subroutine.  Yes, it's 'my' to the handler, but using it inside the
other subroutine makes it kind of like a persistent copy of the very first
usage of the variable.  So, even if the handler gets a new %variable each
time, the closure never sees it.  That's the behavior you're seeing, per
apache process.

I'd suggest making it $variable = {}, then passing $variable into the
subroutine.  That way you declare a subroutine-local (lexically scoped,
declared with 'my') variable inside change_var(), whose lexical lifetime
begins when the subroutine has the path of execution, and whose lexical
lifetime ends as soon as the subroutine returns.  It's set to refer to the
handler's my $variable, each time the subroutine is called, and the
handler()'s $variable is modified through that reference.  

I've modified the subroutine quoted below.  The changes make it so that no
closure of %variable is created, and change_var() is now able to adjust the
per-invocation %$variable properly.  Unchanged lines are still quoted.

[clip: setup, use ...; lines etc]
> sub handler {
> 
my $variable = {};
> $| = 1;
$variable->{'name'} = "value1";

> my $r = shift;
> $r->content_type('text/html');
> $r->send_http_header;
> 
print "Name = " . $variable->{'name'} . "<BR>";
change_var( $variable );
print "Name = " . $variable->{'name'} . "<BR>";

> return OK;
> 
> sub change_var {
     my $variable = shift;
     $variable->{'name'} = "value2";
> }
> 
> }
> 1;
> 
> Thanks in adavance.

Yours was a good simple code sample.  Hopefully this addition to the
mailing list archives will help some folks out in the future.

Randy

Reply via email to