WebDeveloper.com �: Where Web Developers and Designers Learn How to Build Web Sites, Program in Java and JavaScript, and More!   
Web Developer Resource Directory WebDev Jobs
Animated GIFs
CSS Properties
HTML 4.01 Tags
Site Management
WD Forums

    Web Video
    Expression Web



    Forum, Blog, Wiki & CMS

 Site Management
    Domain Names
    Search Engines
    Website Reviews

 Web Development
  Business Issues

    Business Matters

    The Coffee Lounge
    Computer Issues

Perl Style

by Tom Christiansen

  • 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.


  • `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
    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) { ... }


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

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


    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: $!";

HTML5 Development Center

Recent Articles