STYLE GUIDE
Here are some general style guidelines. Treat these as tips for
best practices on Apache::ASP development if you will.
UseStrict
One of perl's blessings is also its bane, variables do not need to be
declared, and are by default globally scoped. The problem with this in
mod_perl is that global variables persist from one request to another
even if a different web browser is viewing a page.
To avoid this problem, perl programmers have often been advised to
add to the top of their perl scripts:
use strict;
In Apache::ASP, you can do this better by setting:
PerlSetVar UseStrict 1
which will cover both script & global.asa compilation and will catch
"use strict" errors correctly. For perl modules, please continue to
add "use strict" to the top of them.
Because its so essential in catching hard to find errors, this
configuration will likely become the default in some future release.
For now, keep setting it.
Do not define subroutines in scripts.
DO NOT add subroutine declarations in scripts. Apache::ASP is optimized
by compiling a script into a subroutine for faster future invocation.
Adding a subroutine definition to a script then looks like this to
the compiler:
sub page_script_sub {
...
... some HTML ...
...
sub your_sub {
...
}
...
}
The biggest problem with subroutines defined in subroutines is the
side effect of creating closures, which will not behave as usually
desired in a mod_perl environment. To understand more about closures,
please read up on them & "Nested Subroutines" at:
http://perl.apache.org/docs/general/perl_reference/perl_reference.html
Instead of defining subroutines in scripts, you may add them to your sites
global.asa, or you may create a perl package or module to share
with your scripts. For more on perl objects & modules, please see:
http://perldoc.perl.org/perlobj.html
Use global.asa's Script_On* Events
Chances are that you will find yourself doing the same thing repeatedly
in each of your web application's scripts. You can use Script_OnStart
and Script_OnEnd to automate these routine tasks. These events are
called before and after each script request.
For example, let's say you have a header & footer you would like to
include in the output of every page, then you might:
# global.asa
sub Script_OnStart {
$Response->Include('header.inc');
}
sub Script_OnEnd {
$Response->Include('footer.inc');
}
Or let's say you want to initialize a global database connection
for use in your scripts:
# global.asa
use Apache::DBI; # automatic persistent database connections
use DBI;
use vars qw($dbh); # declare global $dbh
sub Script_OnStart {
# initialize $dbh
$dbh = DBI->connect(...);
# force you to explicitly commit when you want to save data
$Server->RegisterCleanup(sub { $dbh->rollback; });
}
sub Script_OnEnd {
# not really necessary when using persistent connections, but
# will free this one object reference at least
$dbh = undef;
}