Last week you found out all sorts of good things about mod_perl, but you may be wondering how you get started using it. Let this article be your guide.
mod_perl is about running both scripts and handlers. Although I have started to present mod_perl using scripts because it's easier if you have written CGI scripts before, the more advanced use of mod_perl is about writing handlers. But have no fear. As you will see in a moment, writing handlers is almost as easy as writing scripts.
To create a mod_perl handler module, all I have to do is to wrap the code I have used for the script into a handler subroutine, add a statement to return the status to the server when the subroutine has successfully completed, and append a package declaration at the top of the code.
Just as with scripts you can use either the CGI API you are probably used to (save the following as Rules1.pm):
package ModPerl::Rules1;
use Apache::Constants qw(:common);
sub handler{
print "Content-type: text/plain\r\n\r\n";
print "mod_perl rules!\n";
return OK;
}
1; # satisfy require()
or the Apache Perl API that allows you to interact more intimately with
the Apache core by providing an API unavailable under regular Perl. Of course in the simple example that I show, using any of the approaches is fine, but when you need to use the API, this version of the code should be used (save as Rules2.pm):
package ModPerl::Rules2;
use Apache::Constants qw(:common);
sub handler{
my $r = shift;
$r->send_http_header('text/plain');
print "mod_perl rules!\n";
return OK;
}
1; # satisfy require()
Create a directory called ModPerl under one of the directories in @INC
(e.g. /usr/lib/perl5/site_perl/5.005), and put Rules1.pm Rules2.pm into it, the files should include the code from the above examples.
To find out what the @INC directories are, execute:
Now add the following snippet to httpd.conf to configure mod_perl to execute the ModPerl::Rules::handler subroutine whenever a request to mod_perl_rules1 is made: