Handling “Undefined subroutine called” errors in mod_perl

So I wrote a sample mod_perl handler. It’s a simple hello worldish module. After registering the module in the httpd.conf file and restarting Apache, when I tried to access my module via the specified URL, I got the dreaded 500: Internal Server Error. The Apache error_log indicated “Undefined subroutine &Apache::Hello::handler called”. My file name was Hello.pm and it was placed under the Apache folder under my ~/lib/perl directory at the server root. My program was compiling correctly. Here’s the original code:


#!/usr/bin/perl
use strict;
use Apache::Constants qw(:common);

sub handler{

my $r = shift;

$r->content_type(‘text/html’);

$r->send_http_header;

my $host = $r->get_remote_host;

$r->print(<<END);

<HTML>

<HEAD>

<TITLE>Test mod_perl Handler</TITLE>

</HEAD>

<BODY>

<b>Go mod_perl!!</b>

</BODY>

</HTML>
END

return OK;

}

1;

As you can see the code is very simple. After some googling around, I found out that the real reason for the error was namespace collision. When two scripts or handlers call a function defined in a library without a package definition, or when the same subroutine name is used in two different scrips or handlers being called, there is no clear idea as to which script’s ‘handler’ function to call. So, I added a package definition as shown and it fixed the error.


#!/usr/bin/perl
package Apache::Hello;
use strict;
use Apache::Constants qw(:common);

sub handler{

my $r = shift;

$r->content_type(‘text/html’);

$r->send_http_header;

my $host = $r->get_remote_host;

$r->print(<<END);

<HTML>

<HEAD>

<TITLE>Test mod_perl Handler</TITLE>

</HEAD>

<BODY>

<b>Go mod_perl!!</b>

</BODY>

</HTML>
END

return OK;

}

1;

A good link that talks about troubleshooting runtime mod_perl errors is provided here at Stas Bekman’s mod_perl guide.

One Response to “Handling “Undefined subroutine called” errors in mod_perl”

  1. sandrar Says:

    Hi! I was surfing and found your blog post… nice! I love your blog. :) Cheers! Sandra. R.

Leave a Reply