Making CGI Scripts Efficient

Problem

Your CGI script is called often, and the web server is suffering as a result. You’d like to lessen the load your CGI script causes.

Solution

Use mod_perl in the Apache web server along with the following section in your httpd.conf file:

Alias /perl/ /real/path/to/perl/scripts/

<Location /perl>
SetHandler  perl-script
PerlHandler Apache::Registry
Options ExecCGI
</Location>

PerlModule Apache::Registry
PerlModule CGI
PerlSendHeader On

Discussion

Using the mod_perl Apache web server module, you can write Perl code that will step in at any part of a request’s processing. You can write your own logging and authentication routines, define virtual hosts and their configuration, and write your own handlers for certain types of request.

The snippet above says that requests with URLs starting in /perl/ are actually in /real/path/to/perl/scripts/ and that they should be handled by Apache::Registry. This runs them in a CGI environment. PerlModule CGI preloads the CGI module, and PerlSendHeader On makes most of your CGI scripts work out of the box with mod_perl.

/perl/ works analogously to /cgi-bin/. To make the suffix .perl indicate mod_perl CGI scripts just as the suffix .cgi indicates regular CGI scripts, use the following in your Apache configuration file:

<Files *.perl>
SetHandler  perl-script
PerlHandler Apache::Registry
Options ExecCGI
</Files>

Because the Perl interpreter that runs your CGI script doesn’t shut down when your script is done (as normally ...

Get Perl Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.