Perl Coding Convention

Improvements? Suggestions? email dna@hola.org

General

In general, most of C coding convention apply to Perl coding convention, and one should try to make the perl code looks like c code as mush he can. for example:

  • - Indentation is always one shift-width(4):
  • - case has the same indentatio level and switch
  • - ...

Important note: Perl have many features that allow the programmer to do strange, dangrous and hard to maintain coding. avoid that by using common sense, and by keeping your code close to our c coding conventions (see previous code as a reference). if you have a doubt - ask.

strict

allway use strict package by putting use strict at the beginning of the file.

Functions arguments

Allways declare argument names at the beginning of the function.

sub my_sub { return sys_get(@_); } sub my_sub { my ($cmd) = (@_); return sys_get($cmd); }

Open and close braces

if/else/case/for there is only one line of code, put the opening brace at the same line as the if statement. if there is more than one line, put it on the line below the if statement.

if ($var eq '') { do_something(); } if ($var eq ''){ do_something(); do_something_else(); } if ($var eq ''){ do_something(); } if ($var eq '') { do_something(); do_something_else(); }

if statement

when comparing vars with string value, use perl internal functions (e.g. eq, ne).
when comparing vars with boolean/int value use == or omit the comparison completely (like in C).

if ($var == "a string") ... if ($var eq 2)... if ($var eq "a string") ... if ($var == 2) ... if ($var) ...

switch statement

put the case as the same level of the switch statement.
use else for the default value.

switch($type) { case ('str') { if ($var == 2){ do_something(); } } case ('bool'){ do_something(); } else { err("invalind option"); } }

if you have many short satements, you can put the staement in the same line as the case statement:

switch ($DIST) { case ('APP'){ add_package_APP(); } case ('HOST'){ add_package_HOST(); } case ('SYSSERVER'){ add_package_SYSSERVER(); } else { err("invalid DIST $DIST"); } }

Using eval()

You should not run a 'lot of code' under eval(), since eval() does not exit the programm upon failure (e.g. these is an invalid expression inside eval()).
Hence, you should always check the return value of eval and do the appropriate erorr handling.
Needless to say, eval() should be avoided if at all possible.