tags:

views:

131

answers:

2

Some quote to pick from practical mod_perl

"Usually, a single process serves many requests before it exits, so END blocks cannot be used if they are expected to do something at the end of each request's processing."

So, in my a.cgi script :

my $flag = 1;

END {
    # Value for $flag is undefined, if this script is run under mod_perl. 
    # END block code only executed when process to handle a.cgi exit. 
    # I wish to execute some code, just before process to handle a.cgi exit.
    if ($flag) {
        # clean up code.
    }
}

The book recommences $r->register_cleanup(sub { #cleanup } );

However,

  1. How I can obtain $r in a.cgi script?
  2. Can the subroutine access the my scope flag variable?
  3. Is this $r->register_cleanup shall be placed at a.cgi script? I only want the cleanup code to be executed for a.cgi script. Not the rest.
+4  A: 
  1. my $r = Apache->request;

  2. Yes, but see http://modperlbook.org/html/6-2-Exposing-Apache-Registry-Secrets.html and the next couple of pages, regarding scoping of local variables and functions.

  3. Yes, only register the function if you want it to run.

Stobor
+1  A: 

If I understand this correctly, you have a script you want to run both under mod_perl and as a plain CGI and it sounds like you are using Apache::Registry to do this.

You have cleanup code that you want run only when you are running as CGI script.

You need to detect whether or not you are running under mod_perl. That's fairly easy. The simplest way is to check your environment:

unless ($ENV{MOD_PERL})
{
   #... cleanup code here.
}

You only to register a cleanup handler if you want something to run when your script terminates under Apache::Registry.

If you do want that, you should place your cleanup code into a sub and call that sub from your check in the CGI:

unless ($ENV{MOD_PERL})
{
   cleanup_sub();
}

and from your cleanup handler:

my $r = Apache->request;
$r->register_cleanup(sub { cleanup_sub() } );
Nic Gibson