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

I'm working on a high-throughput web site. The code has some parts that are always the same, such as loading configuration files. It is obviously wasteful to do this on every page load. How can I add some code that will only be executed when Apache is (re)started, and which will set up some variables that can then be accessed by the normal CGI?
  • Comment on How to execute web code on server start only?

Replies are listed 'Best First'.
Re: How to execute web code on server start only?
by Corion (Patriarch) on Jan 18, 2010 at 10:25 UTC

    That's not how CGI works, so it can't be done. You can potentially "pre-cache" some data in a Storable file, or in a database, or set up some environment variables.

    If you want some kind of persistence, you will have to look into mod_perl or FastCGI.

Re: How to execute web code on server start only?
by Anonymous Monk on Jan 18, 2010 at 12:24 UTC
Re: How to execute web code on server start only?
by WizardOfUz (Friar) on Jan 18, 2010 at 13:38 UTC

    The Apache HTTP server lets you define your own environment variables which are accessible from your CGI script just like the standard CGI variables.

      No it doesn't, not from CGI, they don't persist, try it, I just did , it didn't work :)
      #!/usr/bin/perl -- ## ## printenv -- demo CGI program which just prints its environment ## print "Content-type: text/plain; charset=iso-8859-1\n\n"; if( $ENV{QUERY_STRING} ){ $ENV{OneTimeEnvTestWillItPersistProbablyNot}=1; print "so did OneTimeEnvTestWillItPersistProbablyNot persist? thou +ght not\n\n\n"; } else { print "set OneTimeEnvTestWillItPersistProbablyNot=1\n"; print "now append ?foo to the url to see if OneTimeEnvTestWillItPe +rsistProbablyNot persists \n\n\n"; } foreach $var (sort(keys(%ENV))) { $val = $ENV{$var}; $val =~ s|\n|\\n|g; $val =~ s|"|\\"|g; print "${var}=\"${val}\"\n"; }

        You cannot set (global) environment variables from within a CGI script. Please read this.

Re: How to execute web code on server start only?
by my600080 (Novice) on Jan 18, 2010 at 13:48 UTC
    I would say that setting the environment variables should be a way to do this.
      with mod_perl yes, with mod_cgi no