Sample Script
#!/usr/bin/perl -wT
# In the first line above, T causes Perl to check
# for "tainted" data, that is, data from outside the
# script (i.e. user input) that is going to be used
# to affect something else outside the script
# (i.e. writing to a log file)
# You can untaint data by parsing it for unwanted
# characters then saving it to another variable.
# If you are having trouble with a script, try removing
# the T switch to see if that is the problem.
# The w switch in the first line causes warnings about
# script syntax to be printed, if there are any.
# This script does 2 things:
#
#1. It directs fatal errors to the browser,
# so when the script is invoked via the Web,
# a meaningful error message is returned.
# This is useful when developing a script;
# but should be disabled when the script
# is made publicly available.
#
# 2. It will direct any error message the script
# generates to an error log that resides in
# the user's home directory. The file must
# already exist and be "other" writeable.
# Notice that the following is enclosed in
a BEGIN { }
# block that causes it to execute before the rest of
# the script is read.
# This block should be placed in the main script,
# as near the top as practical. Do not place it in
# subroutines or libraries. Always test
# subroutines thoroughly before placing them
# in libraries.
BEGIN {
# define an error log in YOUR home directory
# this is an example where the
# home directory is /domains/domain.com/
my $error_log = "/domains/domain.com/logs/cgi-error.log";
# "my" in the line above makes the variable
$error_log
# local so it only has meaning inside this block.
# See your text for more on variable scope.
# load the CGI::Carp module;
# fatalsToBrowser directs fatal errors to the browser
# carpout is for directing errors to the error log
use CGI::Carp qw(fatalsToBrowser carpout);
open (LOG,">>$error_log") ||
die "couldn't open log file: $!";
carpout(LOG);
# open(...) is used to open a file.
# >> means the new input will be appended what's
# already in the file.
# LOG is a nickname (properly called a
"file handle")
# that is given to the file so it is easy to refer to
# it later, i.e. carpout(LOG) sends the error
# message to the file with the nickname LOG
# || means "or" (as in do this or that)
# die means stop executing the program. You can add
# a message in quotes after the die command.
# $! is a special variable that contains
the current error info
}
# The following line will cause an error.
# It is a call to a sub-routine that does not exist.
# After you have tried this script and received the error message,
# comment out the following line so no error occurs
# and "Hello world!" is printed.
&non_existent_subroutine();
print <<EOT;
Content-type: text/html\n\n
<HTML>
<BODY>
Hello world!
EOT
print "</BODY></HTML>";