Home > Articles > Web Development > Perl

Antibugging in Perl

3.2 Writing Code

Your code should be as pleasing to the eye as possible, if for no other reason than you should like looking at it and not recoil at the prospect of again diving into an eructation of characters on the screen. And let's face it, programs need all the aesthetic help they can get because their primary purpose is utilitarian. Which of the following subroutines do you prefer?

sub iterate (&$$){
for ($_[1] = 0,my $i = 0;$i <= $_[2]; 
$_[1] = ++$i/$_[2]){&{$_[0] };
}
}

or

sub iterate (&$$)
 {
 for ($_[1] = 0, my $i = 0; 
  $i <= $_[2]; 
  $_[1] = ++$i / $_[2])
  {
  &{$_[0]};
  }
 }

3.2.1 Style

The only believable comment to make about style is that you should have one. If you aren't already rabidly attached to a particular style, read the perlstyle manual page and adopt the one shown.

There's no excuse for not indenting properly. I have seen many people in my classes struggling with an exercise, needlessly handicapped because their code was all hugging the left margin for grim death. Regardless of how quick, short, or temporary your code is, indenting it will save more time than it costs. (The Emacs cperl mode will autoindent simply by hitting the TAB key.)

Use a consistent style for each project.

A clean style is a good style, whatever style you choose. A suggestion: write your code as though you expect it to be published (and win the Turing Award)—using white space galore and ample comments.

Pick clear variable names. In general, the less often a variable appears in your code (or the smaller its scope), the longer its name should be since the reader will need more reminding of its purpose. There's nothing wrong though, with single-letter variable names for loop variables (for which they have a long and distinguished history) or mathematical or scientific quantities. ($e=$m*$c**2 makes just as much sense as $energy=$mass* $speed_of_light**2; at least, it does to anyone who should be using code that computes it.)

3.2.2 Help from Your Editor

For those of you concerned about going blind counting and matching (), {}, and [] symbols in your programs, there are tools that can save you from the white cane. A smart editor that can help with some of the routine chores of beautifying a Perl program works wonders. If you have to reindent your code manually every time you remove an outer block, chances are you won't do it. Perl gurus are fond of stating, "Only perl can parse Perl," and as a corollary, no editor can be smart enough to lay out all possible Perl programs correctly. Fair enough; but some of them come close enough to be useful.

One of Peter's favorites is cperl, a Perl mode for Emacs maintained by Ilya Zakharevich. The standard Perl distribution includes an emacs directory that contains the file cperl-mode.el. If your Emacs doesn't already come with cperl, copy this file to wherever you store local Emacs mode files (you can set up a location just for yourself in the .emacs file in your home directory); if you find another version there, determine which cperl-mode.el is more recent. Insert the line

(autoload 'perl-mode "cperl-mode" "alternate mode for editing \ Perl programs" t)

into your .emacs file to enable cperl-mode instead of the regular perl-mode that comes with Emacs.

cperl matches up the various (), [], and {} for you.1 It also performs syntax coloring, so if you configure Emacs to tint all strings in puce and your entire file suddenly blushes, you know you've left a quote mark out somewhere. Most usefully, it tracks nested levels of braces, and a tap of the TAB key takes you to the correct indentation point for the line. This catches all manner of typos, such as the dropped semicolon on line 1:

1 my $marsupial = 'wombat'
2  my $crustacean = 'king crab';

which is exposed when you hit TAB on line 2 and instead of lining up under line 1, the statement indents an extra level because the current statement is incomplete.

cperl does have a few problems, though: if you use the Perl 4 syntax for separating path components in a package qualified identifier with a single quote, it may get confused. But just change the apostrophe (') to colons (::), and you're fine. Using certain characters (like # or ') in character classes in regular expressions confuses it too, but putting backslashes (\) in front of them (backwhacking) resolves the problem.

Other editors we like are: vim/gvim, which does an outstanding job of syntax coloring and has an excellent Windows port; and BBEdit on the Macintosh.

The subject of favorite editors is an intensely religious issue in software development, and you should expect others to disagree with your preference; as long as there are some equally heavyweight developers on your side, it doesn't matter what you pick or what anyone else says.

What should you expect from a good Perl editor? It should warn you when you have mismatched delimiters, it should automatically indent according to the style you want, and it should be as flexible and adaptable to your personal text-editing needs as possible. It should neither insert characters (e.g., invisible binary formatting hints) nor remove any (e.g., trailing spaces) on its own without warning you and giving you the option to disable this functionality selectively or globally.

3.2.3 Think Double

Whether your editor warns you of mismatched delimiters or not, here's a handy tip: enter the closing delimiter at the same time you type the opening one. Then insert what you need between them. Work from the outside in, and your chances of having a grouping typo are greatly reduced. For instance, if you plan to write something that'll end up as:

print table(map { Tr(map td($_), split /[:\s]+/) } <IN>);

(which, using CGI.pm, would print an HTML table from the remaining text coming from the filehandle IN, one row per line, forming table elements from elements separated by white space and/or colons) then your strategy for typing it would follow these steps:

1. 	print table();
2. print table(map {} <>);
3. 	print table(map { Tr() } <IN>);
4. 	print table(map { Tr(map td(), split //) } <IN>);
5. print table(map { Tr(map td($_), split /[:\s]+/) } <IN>);

3.2.4 Clarity

Examine this very simple one-line program:

$x=1; $y=2; $z=$x+$y; print"$x+$y=$z\n";

This isn't difficult to understand: initialize $x and $y, set $z to their sum, then print all three. Suppose we trace its execution through the debugger (see Chapter 7 for a detailed discussion of the debugger).

% perl -de '$x=1; $y=2; $z=$x+$y; print"$x+$y=$z\n"'
main::(-e:1):	$x=1; $y=2; $z=$x+$y; print"$x+$y=$z\n";
 DB<1> n
main::(-e:1):	$x=1; $y=2; $z=$x+$y; print"$x+$y=$z\n"
 DB<1> n
main::(-e:1):	$x=1; $y=2; $z=$x+$y; print"$x+$y=$z\n"
 DB<1> n
main::(-e:1):	$x=1; $y=2; $z=$x+$y; print"$x+$y=$z\n"
 DB<1> n
1+2=3
Debugged program terminated... 
 DB<1> q

What did we observe? The debugger prints the one-line program:

main::(-e:1):	$x=1; $y=2; $z=$x+$y; print"$x+$y=$z\n"

4 times until the expected program output 1+2=3. Why? The debugger displays the next line of code perl executes, not the next command. The program consists of four executable commands, but they're all on the same line; therefore we see the line each time the debugger executes a commend.

Recast the program to one command per line:

$x = 1;
$y = 2;
$z = $x+$y;
print"$x+$y=$z\n";

Then use the debugger. You can either put the four lines in a file or use a shell like the Bourne shell that allows you to type new lines between single quotes.

% perl -d dbformat.pl
main::(dbformat.pl:1):	$x=1;
 DB<1> n
main::(dbformat.pl:2):	$y=2;
 DB<1> n
main::(dbformat.pl:3):	$z=$x+$y;
 DB<1> n
main::(dbformat.pl:4):	print"$x+$y=$z\n";
 DB<1> n
1+2=3
Debugged program terminated... 
 DB<1> q

This is easier to follow. The debugger functioned as it was designed to in both cases, but a style difference made it harder to interpret the debugger's output for the one-liner.

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