Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hi...I'm working on a fairly 'out of the box' CentOS box. It's my first time working with Apache2 / mod_perl2. I started to see some odd behavior and tracked it down to what I believe to be a scope issue. I can boil the problem down with the short script which I'll paste into this message (it's only twelve lines long). Here's the problem:

On the old, production server (running mod_perl and Apache 1.x), both $page vars are always the same: CGI=HASH(0x2b3aa9d0b600) CGI=HASH(0x2b3aa9d0b600)

On the NEW server (NOT running mod_perl, but running Apache 2.x), both $page vars are always the same: CGI=HASH(0x2b3aa9d0b600) CGI=HASH(0x2b3aa9d0b600)

But, on the NEW server (RUNNING mod_perl2 and running Apache 2.x), the $pages are sometimes different, presumably because it is picking the $page variable up from some other thread or process: CGI=HASH(0x2b3aa9d0b600) CGI=HASH(0x2b3aa9fc9a20)

I tried 'compat' and even adjusting PerlInterpScope and neither one of those seemed to do anything (and I felt like I was desperately flailing for a solution instead of actually understanding what was going on…Any light shed would be much appreciated!

Example:
#!/usr/bin/perl use CGI; my $page = new CGI; print $page->header(); print "<html><head></head><body>"; print $page; print "<br>"; test(); print "</body></html>"; sub test{ print $page; }

Replies are listed 'Best First'.
Re: mod_perl2 scope issue?
by ikegami (Patriarch) on Jan 15, 2010 at 02:12 UTC

    At least when you have a problem, stop hiding errors by using "use strict; use warnings;"!

    mod_perl registry scripts are compiled inside as a sub:

    sub { #!/usr/bin/perl use CGI; my $page = new CGI; print $page->header(); print "<html><head></head><body>"; print $page; print "<br>"; test(); print "</body></html>"; sub test{ print $page; } }

    Patterns of the form

    sub named_or_anon { my $x; sub named { ... $x ... } }

    are bad. Perl even warns you about it.

    $ perl -we' sub named_or_anon { my $x; sub named { $x } } ' Variable "$x" will not stay shared at -e line 6.

    Don't use "global" my variables in registry scripts. Using local our $var instead of my $var should do the trick for "global" variables.

      Thank you for the informed reply! I should have included 'use strict;' which I had been using in a previous incarnation of the test script. I didn't know about 'use warnings', though. Thanks for that, too!