Cari di Perl 
    Perl Tutorial
Daftar Isi
(Sebelumnya) Object-Oriented Programming in ...Perl 5 Cheat Sheet (Berikutnya)
Tutorials

Perl style guide

Daftar Isi

NAME

perlstyle - Perl style guide

DESCRIPTION

Each programmer will, of course, have his or her own preferences inregards to formatting, but there are some general guidelines that willmake your programs easier to read, understand, and maintain.

The most important thing is to run your programs under the -wflag at all times. You may turn it off explicitly for particularportions of code via the no warnings pragma or the $^W variableif you must. You should also always run under use strict or know thereason why not. The use sigtrap and even use diagnostics pragmasmay also prove useful.

Regarding aesthetics of code lay out, about the only thing Larrycares strongly about is that the closing curly bracket ofa multi-line BLOCK should line up with the keyword that started the construct.Beyond that, he has other preferences that aren't so strong:

  • 4-column indent.

  • Opening curly on same line as keyword, if possible, otherwise line up.

  • Space before the opening curly of a multi-line BLOCK.

  • One-line BLOCK may be put on one line, including curlies.

  • No space before the semicolon.

  • Semicolon omitted in "short" one-line BLOCK.

  • Space around most operators.

  • Space around a "complex" subscript (inside brackets).

  • Blank lines between chunks that do different things.

  • Uncuddled elses.

  • No space between function name and its opening parenthesis.

  • Space after each comma.

  • Long lines broken after an operator (except and and or).

  • Space after last parenthesis matching on current line.

  • Line up corresponding items vertically.

  • Omit redundant punctuation as long as clarity doesn't suffer.

Larry has his reasons for each of these things, but he doesn't claim thateveryone else's mind works the same as his does.

Here are some other more substantive style issues to think about:

  • Just because you CAN do something a particular way doesn't mean thatyou SHOULD do it that way. Perl is designed to give you severalways to do anything, so consider picking the most readable one. Forinstance

    1. open(FOO,$foo) || die "Can't open $foo: $!";

    is better than

    1. die "Can't open $foo: $!" unless open(FOO,$foo);

    because the second way hides the main point of the statement in amodifier. On the other hand

    1. print "Starting analysis\n" if $verbose;

    is better than

    1. $verbose && print "Starting analysis\n";

    because the main point isn't whether the user typed -v or not.

    Similarly, just because an operator lets you assume default argumentsdoesn't mean that you have to make use of the defaults. The defaultsare there for lazy systems programmers writing one-shot programs. Ifyou want your program to be readable, consider supplying the argument.

    Along the same lines, just because you CAN omit parentheses in manyplaces doesn't mean that you ought to:

    1. return print reverse sort num values %array;
    2. return print(reverse(sort num (values(%array))));

    When in doubt, parenthesize. At the very least it will let some poorschmuck bounce on the % key in vi.

    Even if you aren't in doubt, consider the mental welfare of the personwho has to maintain the code after you, and who will probably putparentheses in the wrong place.

  • Don't go through silly contortions to exit a loop at the top or thebottom, when Perl provides the last operator so you can exit inthe middle. Just "outdent" it a little to make it more visible:

    1. LINE:
    2. for (;;) {
    3. statements;
    4. last LINE if $foo;
    5. next LINE if /^#/;
    6. statements;
    7. }
  • Don't be afraid to use loop labels--they're there to enhancereadability as well as to allow multilevel loop breaks. See theprevious example.

  • Avoid using grep() (or map()) or `backticks` in a void context, that is,when you just throw away their return values. Those functions allhave return values, so use them. Otherwise use a foreach() loop orthe system() function instead.

  • For portability, when using features that may not be implemented onevery machine, test the construct in an eval to see if it fails. Ifyou know what version or patchlevel a particular feature wasimplemented, you can test $] ($PERL_VERSION in English) to see if itwill be there. The Config module will also let you interrogate valuesdetermined by the Configure program when Perl was installed.

  • Choose mnemonic identifiers. If you can't remember what mnemonic means,you've got a problem.

  • While short identifiers like $gotit are probably ok, use underscores toseparate words in longer identifiers. It is generally easier to read$var_names_like_this than $VarNamesLikeThis, especially fornon-native speakers of English. It's also a simple rule that worksconsistently with VAR_NAMES_LIKE_THIS.

    Package names are sometimes an exception to this rule. Perl informallyreserves lowercase module names for "pragma" modules like integer andstrict. Other modules should begin with a capital letter and use mixedcase, but probably without underscores due to limitations in primitivefile systems' representations of module names as files that must fit into afew sparse bytes.

  • You may find it helpful to use letter case to indicate the scopeor nature of a variable. For example:

    1. $ALL_CAPS_HERE constants only (beware clashes with perl vars!)
    2. $Some_Caps_Here package-wide global/static
    3. $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().

    You can use a leading underscore to indicate that a variable orfunction should not be used outside the package that defined it.

  • If you have a really hairy regular expression, use the /x modifier andput in some whitespace to make it look a little less like line noise.Don't use slash as a delimiter when your regexp has slashes or backslashes.

  • Use the new and and or operators to avoid having to parenthesizelist operators so much, and to reduce the incidence of punctuationoperators like && and ||. Call your subroutines as if they werefunctions or list operators to avoid excessive ampersands and parentheses.

  • Use here documents instead of repeated print() statements.

  • Line up corresponding things vertically, especially if it'd be too longto fit on one line anyway.

    1. $IDX = $ST_MTIME;
    2. $IDX = $ST_ATIME if $opt_u;
    3. $IDX = $ST_CTIME if $opt_c;
    4. $IDX = $ST_SIZE if $opt_s;
    5. mkdir $tmpdir, 0700or die "can't mkdir $tmpdir: $!";
    6. chdir($tmpdir) or die "can't chdir $tmpdir: $!";
    7. mkdir 'tmp', 0777or die "can't mkdir $tmpdir/tmp: $!";
  • Always check the return codes of system calls. Good error messages shouldgo to STDERR, include which program caused the problem, what the failedsystem call and arguments were, and (VERY IMPORTANT) should contain thestandard system error message for what went wrong. Here's a simple butsufficient example:

    1. opendir(D, $dir) or die "can't opendir $dir: $!";
  • Line up your transliterations when it makes sense:

    1. tr [abc]
    2. [xyz];
  • Think about reusability. Why waste brainpower on a one-shot when youmight want to do something like it again? Consider generalizing yourcode. Consider writing a module or object class. Consider making yourcode run cleanly with use strict and use warnings (or -w) ineffect. Consider giving away your code. Consider changing your wholeworld view. Consider... oh, never mind.

  • Try to document your code and use Pod formatting in a consistent way. Hereare commonly expected conventions:

    • use C<> for function, variable and module names (and moregenerally anything that can be considered part of code, like filehandlesor specific values). Note that function names are considered more readablewith parentheses after their name, that is function().

    • use B<> for commands names like cat or grep.

    • use F<> or C<> for file names. F<> shouldbe the only Pod code for file names, but as most Pod formatters render itas italic, Unix and Windows paths with their slashes and backslashes maybe less readable, and better rendered with C<>.

  • Be consistent.

  • Be nice.

Page index
 
Source : perldoc.perl.org - Official documentation for the Perl programming language
Site maintained by Jon Allen (JJ)     See the project page for more details
Documentation maintained by the Perl 5 Porters
(Sebelumnya) Object-Oriented Programming in ...Perl 5 Cheat Sheet (Berikutnya)