Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much
 
PerlMonks  

Re: Variable will not stay shared in a sporadically crashing CGI

by Corion (Patriarch)
on Oct 02, 2017 at 12:54 UTC ( [id://1200518]=note: print w/replies, xml ) Need Help??


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.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1200518]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others cooling their heels in the Monastery: (5)
As of 2024-04-24 08:18 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found