Writing mod perl-ready CGI scripts
From Dev411: The Code Wiki
Standard Perl CGI scripts can get a large performance boost when run under mod_perl. The three general ways to run a script under mod_perl are:
- PerlRun with PerlRunOnce (worst performance)
- PerlRun
- Registry (best performance)
You can ensure your CGI script will be mod_perl Registry compliant by following just a few guidelines when developing under CGI. mod_perl Registry works by wrapping the script in the hander() subroutine which is the key to understanding the coding guidelines that are needed.
| Table of contents |
Guidelines
Use strict and use warnings
The following lines will catch many potential pitfalls in your script with the strict and warnings pragmas:
use strict; use warnings;
Avoid global variables
Because mod_perl Registry nests scripts in the hander() subroutine, use of global variables can cause various problems. Variables that are global when run under CGI now become lexical under Registry.
You can avoid global variables by passing variables to your subroutines. An easy way to check you haven't missed any variables is to wrap the main body of your script in a main subroutine' (similar to how your code would be wrapped by the hander() Registry routine).
An example script:
#!/usr/bin/perl
my $i = rand();
print_num();
sub print_num {
print "$i\n";
}
The script with the main subroutine and variable passing:
#!/usr/bin/perl
use strict;
use warnings;
sub main {
my $i = rand();
print_num($i);
}
main();
sub print_num {
my $i = shift;
print "$i\n";
}
Avoid __END__ and __DATA__
Since your script is now encapsulated in the handler() subroutine, you can no longer use __END__ and __DATA__ tags
Further Reading / External Links
The basics of what changes (with mod_perl) (flatlineconstruct.com) (http://www.flatlineconstruct.com/talk/understanding_mod_perl/code_changes.html)
