Home > Articles > Web Development > Perl

Like this article? We recommend

Like this article? We recommend

Writing mod_perl Scripts

In general, writing CGI scripts to run under mod_perl doesn’t differ much from writing them for execution under a standalone Perl process.Therefore, if you create a standalone script in the cgi-bin directory, you often can expect that moving it to the cgi-perl directory won’t cause problems, the script will just run faster.The perl-test.pl script we used earlier to test the mod_perl configuration was an example of this: It functioned properly whether run from cgi-bin or from cgi-perl.You can try this with other scripts as well. For example, you can move the scripts developed in Chapter 2 from cgi-bin to cgi-perl to see whether they work properly.
That’s not to say that there are never any problems using CGI scripts under mod_perl.This section describes things to guard against so your scripts don’t cause problems for themselves, other scripts, or your Web server. It discusses the issues you should be aware of for the applications in this book.You might trip over others in your own scripts, however; so for additional information, check the mod_perl_to_cgi and mod_perl_traps documents listed in Appendix B.

Script-Writing Shortcuts

When you write scripts for mod_perl, you can use certain shortcuts as compared to writing them for standalone execution:

  • A mod_perl script must be executable, just like its standalone counterpart, but you don’t need to include the initial #! line that specifies the pathname to the Perl interpreter.

  • For any directory added to the Perl search path with a use lib statement in the startup file, you don’t need to add it in any of your scripts.

Of course, if you take advantage of these shortcuts, you’ll need to add the #! and use lib lines back in if you decide later to use your scripts as standalone CGI programs (for example, to use them on a host that supports only that execution mode). In this book, scripts written for mod_perl will begin with the #! line and will include any necessary use lib line, even though they don’t strictly need them.That way you’ll more easily be able to use them even if you don’t install mod_perl, by moving them to the cgi-bin directory instead.

Diagnostic Output Generation

It’s often useful to tell Perl to generate error messages that help you determine that your scripts have problems and what to do about it.You may find the following techniques useful for getting diagnostic information and debugging your scripts:

  • Use the -w option on the #! line at the beginning of your scripts to tell Perl to emit warnings for questionable constructs:

    #! /usr/bin/perl -w

    mod_perl doesn’t use the pathname, but it will notice the -w option and turn on warning mode.

  • Include a use diagnostics line to tell Perl to print suggestions about the causes of problems:

    use diagnostics;

  • Install the Apache::DBdebugger module and preload it in the mod_perl startup file.This module isn’t included with Apache or mod_perl by default, but you can
    get it from http://cpan.perl.org/.

Output resulting from these techniques will go to the Apache error log, so you’ll need to look there for diagnostic messages. Naturally, you should try to write your scripts to eliminate warnings if possible. If you use the -w option on the #! line, the error log can become useless if you have so many warnings being produced that it becomes difficult to tell what’s important and what isn’t.Try to modify your scripts to make the warnings go away.

Script Environment Contamination

With a standalone script, the environment provided by the external Perl process that executes the script goes away when the script terminates.The processes are independent and don’t affect each other.With mod_perl, this is not true, because a given httpd process can run several scripts over the course of its lifetime, and there is state information in the Perl interpreter that persists from request to request.This is essential behavior for implementing some kinds of services such as persistent database connections, but it can lead to problems as well. If you’re sloppy in your programming, one script can pollute the environment for subsequent scripts. Here’s a simple example:

#! /usr/bin/perl -w 
print “Content-Type: text/html\n\n”; 
print $x++, “\n”;

Put this script in your cgi-bin directory as increment.pl, and then request it several times in quick succession.You’ll see the value 0 in your browser window each time. Then move it to cgi-perl and request it from there several more times. Now you’ll see a series of numbers that is “sort of ” random but generally increasing. (The order depends on the order in which the httpd children are selected to process your requests.) The reason this occurs is that $x is a global variable but is never initialized. The first time any given child executes increment.pl, the value of $x is 0.The next time, the script inherits the previous value and increments that.

Don’t use variables as global variables without declaring them as such or without initializing them first.The increment.pl script doesn’t follow this principle, so it needs some modification to be a better citizen. Fortunately, that’s easy to do. Just declare $x to be global explicitly with use vars, and then initialize it:

#! /usr/bin/perl -w 
use strict; 
use vars qw($x); 
$x = 0;print “Content-Type: text/html\n\n”; 
print $x++, “\n”;

The use strict line isn’t actually required to make the script yield consistent results (0 each time it’s invoked); it’s just good programming practice to use it.

When you initialize a variable, make sure it’s initialized every time your script executes.The following bit of code sets $x to 1, but only if some_test() succeeds:

use vars qw($x); 
$x = 1 if some_test ();

The problem is that $x remains set to 1 even if some_test() fails on every subsequent invocation of the script. Suppose what some_test() does is check a user-supplied password and return true if the password is okay. After $x gets set, it remains set, even if the next person to come along provides an incorrect password! The following code handles the situation properly:

use vars qw($x); 
$x = 0; $x = 1 if some_test ();

So does this:

use vars qw($x); 
$x = some_test () ? 1 : 0;

The basic principle here is that you don’t want to start making decisions based on variable values until you know they’ve been initialized properly.

When you’re trying to determine the cause of problems due to shared script environments, you may find it useful to stop Apache and restart it using httpd -X.The -X option tells Apache to run as a single process rather than in the usual parent-children configuration.That makes shared-environment problems show up more quickly. (You should do this only on a development server, not a production server.)

Variable Scope Effects

mod_perl runs scripts by wrapping them inside a function (one reason for this is that it can assign each script its own unique namespace).This can cause problems due to variable scope. Here is a simple program that illustrates the effect:

 #! /usr/bin/perl -w 
print “Content-Type: text/html\n\n”; 
my $x = 0;
f (); exit (0); sub f { print $x++, “\n”; }

If you request this script several times from your browser, the script doesn’t print 0 each time as you would expect. Instead, the values increase.This occurs even though the variable $x is explicitly initialized to 0. A clue that something is wrong here will be found in the Apache error log:

Variable “$x” will not stay shared at line 5.

(The line number is off due to the script being executed inside the wrapper function.) The difficulty here is that when the script is run inside a wrapper by mod_perl, your entire script becomes a single function, and any functions in the script become inner subroutines.That means f() is an inner subroutine that references a lexically scoped my() variable belonging to its parent subroutine and that isn’t passed to it as an argument.As a result, the inner subroutine sees $x with the correct value the first time the script runs. After that, the variable becomes unshared and the inner subroutine continues to use its own unshared value of $x on subsequent invocations.This issue is discussed in more detail in the mod_perl Guide, along with various solutions to the problem. One way to avoid the difficulty is to change the declaration of $x to be global:

 #! /usr/bin/perl -w 
print “Content-Type: text/html\n\n”; 
use vars qw($x);
 $x = 0; 
f (); 
exit (0);

sub f 
{
   print $x++, “\n”;
}

You can declare a variable using my if you want to, as long as you pass it as an argument to any subroutine that needs it, instead of accessing it directly from the subroutine as a global variable. (That’s actually the way I prefer to write scripts, which is why you won’t see many instances of use vars in this book.) If you want to modify the variable inside the subroutine, pass it by reference:

 #! /usr/bin/perl -w 
print “Content-type: text/html\n\n”; 
my $x = 0; 
f (\$x); 
exit (0); 

sub f 
{ 
my $x_ref = shift; 

     print ++${$x_ref}, “\n”; 
} 

Code Caching Effects

Recall that mod_perl caches compiled scripts.This helps it run scripts faster, but what happens if you change a script? Does mod_perl continue to execute the cached version? Nope. Apache::Registry keeps track of the scripts that it has run and checks the modification date of the original file when a script is requested again. If the date has changed, it recompiles the script and the new version is used instead.You can verify this for yourself. Request a script, and then change it and click the Reload button in your browser.You should see the changed output.Then change the script back and click Reload again.You should see the original output.That’s what you expect and want to happen.2

However, this behavior doesn’t apply to modules pulled into your script via use or require. If you change those files, the changes won’t be noticed until you restart the server. Another workaround for this problem is to use the Apache::StatINC module, which forces Apache to check the last modification time even for modules referenced from use or require statements.This is a technique best used on a development server, because it slows down Apache. Run perldoc Apache::StatINC from the command line for more information.

Script caching also is responsible for another mysterious problem. If you use or require a library file, that file’s code is pulled in to your script, compiled, and cached, as usual. If the file doesn’t contain a package declaration to specify a namespace, however, the code goes into your script’s own namespace.This is main when you run scripts in standalone mode, but scripts run in their own unique namespace under mod_perl. If your script is called script.pl, for example, the namespace might be &Apache::ROOT::cgi_2dperl::script_2epl. Normally, having unique namespaces per script is a good thing, because it helps keep scripts that are run under a given httpd child from colliding with each other in the main namespace. But it causes a problem for unpackaged library code. Here’s why: Suppose you run your script script.pl that uses a library file MyLib.pm containing a function lib_func(). script.pl will execute properly. Now suppose you have a second script, script2.pl, that wants to use MyLib.pm, too.When the second script, executes, mod_perl, sees the use or require line for the library file, notices that the file has already been processed and cached, and doesn’t bother to recompile it.Then when script2.pl calls lib_func() from the library file, an error occurs:

[error] Undefined subroutine
&Apache::ROOT::cgi_2dperl::script2_2epl::lib_func called

This happens because functions in the library file have been compiled, but they’re in the namespace for script.pl, not script2.pl.To fix this problem, make sure the library file includes a package declaration, and then invoke its functions using the package identifier. MyLib.pm can be written like this:

package MyLib;


sub lib_func 
{
   ... 
} 
...

After making that change, your scripts should invoke MyLib::lib_func() rather than lib_func().

Persistent Database Connections

Normally, scripts that use MySQL open a connection to the MySQL server, access the database, and close the connection. Such connections are non-persistent.You can use persistent database connections instead if you want to share connections among database scripts and minimize connection setup overhead. However, you don’t actually make any changes to your scripts to do this. Instead, preload the Apache::DBImodule from your mod_perl startup file:

use Apache::DBI ();

Alternatively, use a PerlModule directive in httpd.conf:

PerlModule Apache::DBI

(In either case, if you preload both Apache::DBI and DBI, you should load Apache::DBI first.) After you restart Apache to make the change take effect, each child httpd process will manage a pool of open connections to the MySQL server.This happens transparently to your scripts. DBI’s disconnect() method is overridden to become a no-op, and the connect() method is overridden with one that checks whether the database you’re connecting to is already open. If so, the connection is reused. For more information, run perldoc Apache::DBI from the command line.

Running Scripts with Special Privileges

You can invoke a standalone Perl script under Apache’s suEXEC mechanism to run them under a particular user ID if the script needs higher security or greater privileges.This isn’t possible with mod_perl scripts because they run within Apache, and Apache can’t change its own user ID (unless you run it as root, which is a huge security risk). A workaround for this in some cases is to run a helper application using suEXEC for that part of your script’s task that requires special privileges. Or, if your script doesn’t actually require mod_perl, put it in the cgi-bin directory and launch it with suEXEC as a standalone script.

You should now be able to install mod_perl if you want to. And by bearing in mind the discussion just presented concerning mod_perl-related issues to watch out for, you should be able to write scripts that run properly whether or not they run under mod_perl. Of course, none of the programs shown in this chapter really do much of anything; they are intended only to illustrate various aspects of mod_perl’s behavior. In the next chapter we’ll discuss the design of form-based scripts, an extremely common type of Web application that enables you to accomplish real work.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020