in reply to Perl complaining about vars not staying shared

You can find the explanation of such behavior in Paul DuBois's book "MySQL and Perl for the Web". Basically:

mod_perl runs scripts by wrapping them inside a function (one reason for this is that it can assign each script its own unique namespace). This can cause problems due to variable scope. Here is a simple program that illustrates the effect:
#!/usr/bin/perl -w print "Content-Type: text/html\n\n"; my $x = 0; f (); exit (0); sub f { print $x++, "\n"; }
If you request this script several times from your browser, the script doesn’t print 0 each time as you would expect. Instead, the values increase. This occurs even though the variable $x is explicitly initialized to 0. A clue that something is wrong here will be found in the Apache error log:

Variable "$x" will not stay shared at line 5.

(The line number is off due to the script being executed inside the wrapper function.) The difficulty here is that when the script is run inside a wrapper by mod_perl, your entire script becomes a single function, and any functions in the script become inner subroutines. That means f() is an inner subroutine that references a lexically scoped my() variable belonging to its parent subroutine and that isn’t passed to it as an argument. As a result, the inner subroutine sees $x with the correct value the first time the script runs. After that, the variable becomes unshared and the inner subroutine continues to use its own unshared value of $x on subsequent invocations. This issue is discussed in more detail in the mod_perl Guide, along with various solutions to the problem.

I don't know which solutions are offered in the mod_perl Guide, but Paul DuBois offers two:

Quick update: I rushed myself a bit, as you don't seem to be using mod_perl. If what I wrote turns out to be irrelevant to your problem, I'll suffer public spanking. Of course, you're invited.

Replies are listed 'Best First'.
Re^2: Perl complaining about vars not staying shared
by Andre_br (Pilgrim) on Jan 30, 2005 at 04:34 UTC
    Thank you all!

    In fact, Fang, I am not using mod_perl yet. But I do plan to. The tip Tan. gave solved the problem: naming the sub with my with a variable name. Thanks a lot, Tan. The point is tricky is not to forget the ; after the closing } , otherwise it won´t work.

    Take care!

    André