WebDeveloper.com ®: Where Web Developers and Designers Learn How to Build Web Sites, Program in Java and JavaScript, and More!   
Web Developer Resource DirectoryWebDev Jobs  
Animated GIFs
CSS
CSS Properties
Database
Design
Flash
HTML
HTML 4.01 Tags
JavaScript
.NET
PHP
Reference
Security
Site Management
Video
XML/RSS
WD Forums
 Client-Side
  Development

    CSS
    Graphics
    HTML
    JavaScript
    XML
    Dreamweaver/FrontPage
    Multimedia
    Web Video
    General
    Accessibility

 Server-Side
  Development

    ASP
    Perl
    PHP
    .NET
    Java
    SQL
    Other

 Web Development
  Business Issues

    Business Matters
    Website Reviews

 E-Commerce
    Domain Names
    Search Engines

 Etc.
    Computer Issues
    Forum Software
    Feedback
    The Coffee Lounge



Script Downloads
A Good Enough addEvent

Featured: July 25, 2008
Description: This function makes it easy to add events without tripping over existing ones. Easy to implement.

Get Script

Hosting Search
Unix   Windows
PHP   Webmail

Sign up for the free WebDeveloper E-mail newsletter!


JupiterWeb Commerce
Partners & Affiliates
Partner With Us
Dental Insurance
Auto Insurance Quote
Promote Your Website
Compare Prices
KVM Switches
Corporate Gifts
KVM over IP
Calling Cards
Memory Upgrades
Online Shopping
Promotional Golf
Server Racks
Best Price
Home Improvement

internet.com
IT
Developer
Internet News
Small Business
Personal Technology
International

Search internet.com
Advertise
Corporate Info
Newsletters
Tech Jobs
E-mail Offers

Just because Web sites are easy to build these days, that doesn't mean it's easy to build a quality Web site that meets your business objectives.

Before developing your next Web site, or redesigning an existing site, download this Internet.com eBook to guide you through the process and plan your project, whether you're developing a site in-house or outsourcing the project.
Register now for your free Internet.com membership to download your complimentary eBook. Membership will also give you access to:

eBook library         Whitepapers         Webcasts
Newsletters         WinDrivers

Perl Style

By Tom Christiansen
This article first appeared November 21st, 1998.

  • Style can easily become a religious issue.
  • What I am about to tell you is mostly my opinion. It includes both general philosophy and concrete tips.
  • Warning: I may not always follow my own tips. :-)
  • I do not expect all of you to agree with me all the time. Choose a style and stick with it. Consistency is critical.
  • I owe indirectly K&P, K&R, S&W, Rob Pike, and Larry Wall for laying the foundations, and directly Jon Orwant, Mark-Jason Dominus, and Nat Torkington for reviewing early versions of these notes.
  • `Under no circumstances should you program the way I say to because I say to; program the way you think expresses best what you're trying to accomplish in the program. And do so consistently and ruthlessly.' --Rob Pike

Program Perl, Not C / BASIC / Java or Pascal!

  • 'Just because you can do something a particular way doesn't mean you should do it that way.' --Programming Perl
  • If you find yourself writing code that looks like C code, or BASIC, or Java, or Pascal, you are probably short-changing yourself. You need to learn to program idiomatic Perl -- which does not mean obfuscatory Perl. It means Perl in its own idiom: native Perl.
  • Fall not into the folly of avoiding certain Perl idioms for fear that someone who maintains your Perl code won't understand it because they don't know Perl. This is ridiculous! That person shouldn't be maintaining a language they don't understand. You don't write your English so that someone who only speaks French or German can understand you, or use Latin letters when writing Greek.

Elegance

  • `It is very hard to get things both right (coherent and correct) and usable (consistent enough, attractive enough).' --Dennis Ritchie
  • Strive always to create code that is functional, minimal, flexible, and understandable -- not necessarily in that order.
  • Think first. Then hack. Now throw it out. Repeat. Fred Brooks says, `Build one to throw away.' Always rewrite your code from scratch, preferably twice. just as did it with drafts of papers in grammar school. It improves understanding, gets the creative juices flowing, and produces a far finer end-product.
  • Sometimes making code shorter improves maintainability; other times it does not.

Defensive Programming

  • use strict
  • #!/usr/bin/perl -w
  • Check all syscall return values, printing $!
  • Watch for external program failures in $?
  • Check $@ after eval"" or s///ee.
  • Parameter asserts
  • #!/usr/bin/perl -T
  • Always have an else after a chain of elsifs
  • Put commas at the end of lists to so your program won't break if someone inserts another item at the end of the list.

The Art of Commenting Code

  • Explain what the code does, don't just perl2englishify.
  • Eschew gaudy block banners.
  • Use comments in regexes with /x.
  • Comment entire blocks, not single lines.
  • `Comments on data are usually much more helpful than on algorithms.' (Rob Pike)
  • `Basically, avoid comments. If your code needs a comment to be understood, it would be better to rewrite it so it's easier to understand.' (Rob Pike)

On the Naming of Names (Form)

  • `I eschew embedded capital letters in names; to my prose-oriented eyes, they are too awkward to read comfortably. They jangle like bad typography.' (Rob Pike)
  • `IEschewEmbeddedCapitalLettersInNames ToMyProseOrientedEyes TheyAreTooAwkwardToReadComfortably TheyJangleLikeBadTypography.' (TheAntiPike)
  • While short identifiers like $gotit are probably ok, use underscores to separate words. It is generally easier to read $var_names_like_this than $VarNamesLikeThis, especially for non-native speakers of English. It's also a simple rule that works consistently with VAR_NAMES_LIKE_THIS.
  • You may find it helpful to use letter case to indicate the scope or nature of a variable. For example:$ALL_CAPS_HERE
    constants only (beware clashes with perl vars!)
    $Some_Caps_Here package-wide global/static
    $no_caps_here
    function scope my() or local() variables
  • Function and method names seem to work best as all lowercase. E.g., $obj->as_string().

On the Naming of Names (Content)

  • `Procedure names should reflect what they do; function names should reflect what they return.' --Rob Pike.
  • Name objects so that they read well in English. For example, predicate functions should usually be named with `is', `does', `can', or `has'. Thus, &is_ready is better than &ready for the same function,
  • Therefore, &canonize as a void function (procedure), &canonical_version as a value-returning function, and &is_canonical for a boolean check.
  • The &abc2xyz and &abc_to_xyz forms are also well established for conversion functions or hash mappings.
  • Hashes usually express some property of the keys, and are used with the English word `of' or the possessive form. Name hashes for their values, not their keys.

    GOOD: %color = ('apple' => 'red', 'banana' => 'yellow');
    print $color{'apple'}; # Prints `red'

    BAD: %fruit = ('apple' => 'red', 'banana' => 'yellow');
    print $fruit{'apple'}; # Prints `red'

Length of Variable Names

  • `The appropriate length of a name is inversely proportional to the size of its scope.' --Mark-Jason Dominus
  • Length of identifiers is not a virtue; clarity is. Don't write this:

    for ($index = 0; $index < @$array_pointer; $index++) {
    $array_pointer->[$index] += 2; }

    When you should write:

    for ($i = 0; $i < @$ap; $i++) {
    $ap->[$i] += 2; }

    (One could argue for a better name than $ap, though. Or not.)

  • Global variables deserve longer names than local ones, because their context is hard to see. For example, %State_Table is a program global, but $func might be a local state pointer.foreach $func (values %State_Table) { ... }

Parallelism

  • Code legibility is dramatically increased by consistency and parallelism. Compare

    my $filename = $args{PATHNAME};
    my @names = @{ $args{FIELDNAMES} };
    my $tab = $args{SEPARATOR};

    with

    my $filename = $args{PATHNAME};
    my @names = @{$args{FIELDNAMES}};
    my $tab = $args{SEPARATOR};

  • Line up your # comments or your || die all at one column:

    socket(SERVER, PF_UNIX, SOCK_STREAM, 0) || die "socket $sockname: $!";
    bind (SERVER, $uaddr) || die "bind $sockname: $!";
    listen(SERVER,SOMAXCONN) || die "listen $sockname: $!";




Acceptable Use Policy

JupiterOnlineMedia

internet.comearthweb.comDevx.commediabistro.comGraphics.com

Search:

Jupitermedia Corporation has two divisions: Jupiterimages and JupiterOnlineMedia

Jupitermedia Corporate Info


Legal Notices, Licensing, Reprints, & Permissions, Privacy Policy.

Web Hosting | Newsletters | Tech Jobs | Shopping | E-mail Offers