in reply to Variable will not stay shared in a sporadically crashing CGI

Apache resp. mod_perl is wrapping your CGI script in a subroutine to repeatedly call it. This also explains why you have the problem with the "global" lexical $cgi.

Your workaround of explicitly passing around the variable is a good one in my opinion.

Replies are listed 'Best First'.
Re^2: Variable will not stay shared in a sporadically crashing CGI
by Anonymous Monk on Oct 02, 2017 at 13:34 UTC
    Apache resp. mod_perl is wrapping your CGI script in a subroutine to repeatedly call it.
    This is the right explanation, but maybe the meaning is not completely clear. When you use Apache::Registry to run your script, it literally adds a set of brackets around your script and makes the whole thing into a sub, kind of like this:
    sub handler { #!/usr/bin/perl use strict; use warnings; use CGI; my $cgi = new CGI; print_document_header(); sub print_document_header { print $cgi->header( -type => 'text/html' ), "\n"; } }
    Your workaround of explicitly passing around the variable is a good one in my opinion.
    I completely agree, but if you're allergic to good programming practice you can just use our $cgi instead of my $cgi.
      you can just use our $cgi instead of my $cgi

      Locutus: Please, avoid globals - the "best" way to do it is to pass $cgi as an argument to the subroutines.

        I'd say the problem is inter-mixing lexicals my $cgi with package symbols like named subs like sub print_document

        Changing to lexicals holding anonymous sub refs my $print_document = sub {} would solve the OP'S problem too.

        Having persistent shared globals can be a desired effect. (Initialization overhead, communication channel)

        Cheers Rolf
        (addicted to the Perl Programming Language and ☆☆☆☆ :)
        Je suis Charlie!

        This is getting a bit off-topic, but some globals are ok. Novice programmers don't always know when they're safe and when they aren't, and they're often too timid to change a global to a local when it really needs to be done. That's why we advise people not to use globals at all. But CGI is probably safe as a global, because there's no reason to have two of them in your program.