Perl Coding Guidelines
Perl Coding Guidelines
Version 1.0
Amit Roy
amitrupu@gmail.com
Perl Coding Guidelines
Index
1 Introduction.........................................................................................................2
2 Golden rules ........................................................................................................2
2.1 Change the #! line ........................................................................................2
2.2 Enable warning ............................................................................................2
2.3 Check the Perl version ..................................................................................3
2.4 Use comments and indentation to improve readability ...................................3
2.5 Use my and use strict ................................................................................3
2.6 Use Hungarian like notation for variable naming ...........................................4
2.7 Differentiate between numeric and string comparison ...................................4
2.8 Use {} for extracting variable name ................................................................4
2.9 Understanding scalar context of list ..............................................................5
2.10 The ".." list creation operator .........................................................................5
2.11 Use quote like operator wherever possible .....................................................5
2.12 defined, exists and meaning of truth .............................................................6
2.13 Use explicit item variables in foreach, while context ......................................6
2.14 Better use of regular expressions ..................................................................7
2.15 Use Data::Dumper for debugging complex data structures .............................7
2.16 All subroutine definitions should be clubbed together ...................................8
2.17 Pass reference to list in subroutine argument ................................................8
2.18 Type check for subroutine arguments ...........................................................9
2.19 Use Storable module for dump / restore object model ...................................9
2.20 Use warn and die for error handling ..............................................................9
2.21 Using built-in functions rather than system() ................................................9
2.22 Check status of system() call or `` ................................................................ 10
2.23 Use FileHandle module instead of *FILE globs ............................................. 10
2.24 Dont forget to return 1 at the end of package .............................................. 10
2.25 Understand difference between use and require .......................................... 10
2.26 Use Getopt package for command line parsing ............................................ 11
2.27 Use POD documentation ............................................................................. 11
Amit Roy 1
Perl Coding Guidelines
1 Introduction
Perl is a high-level scripting language with enormous syntax and semantic features. Perl
syntax can make a code very powerful but simultaneously unreadable, even to the
owner after a while.
This is why it is recommended to follow a guideline during Perl coding. This would help
to:
Improve readability of code
Maintain the code by multiple developers
Provide bug free support
Restructure or package the code in future
2 Golden rules
#!/bin/perl
Still the problem persists if you want to use your custom Perl installation area. Then
you have to change this #! line with your Perl path. A better solution is to use
#!/bin/env perl
as the first line which automatically takes the Perl binary path from $path environment
variable. So now you dont have to change the Perl path in the code, but set your $path
environment variable so that your installation gets priority, i.e.
use warnings;
Amit Roy 2
Perl Coding Guidelines
perl v
If your system has an old version of Perl, download latest version of Perl and use that as
instructed in 2.1.
You can also get the Perl version from within Perl code using built-in variable $],
print $].\n;
my $VERSION = 5.006;
require $VERSION;
#!/bin/env perl
use 5.008; # check version
use strict;
use warnings;
# Global variables
my ($gbCheckAll, $gbIsFull);
if (($gbCheckAll && $gbIsFul) {
# Do computation
my $nSum = $nItemA + $nItemB;
}
$bIsFull = 1;
if ($bCheckAll && $bIsFul) { } # one l is missing
To ensure the use of my strictly in code (whenever he wants to declare a variable) and
catch above error, one can use use strict; in code.
Amit Roy 3
Perl Coding Guidelines
use strict;
my $bIsFull = 1;
if ($bCheckAll && $bIsFul) ( # will be caught at compilation time
}
A better idea is to use Hungarian notation for variable naming, which will, by-name
specify the type of value it is holding. That is, the first character (which will be s, n,
b, l, h, p etc) will indicate the type. For example,
It is recommended that you initialize all global variables during declaration. Otherwise,
before reading you should be careful and use (!defined $g<VariableName>) to check if
no value is there.
Note, non-string scalar (i.e. reference) comparison can be done using numeric
comparison operators.
my $sCompany = Self;
print ${sCompany}Systems; # not print $sCompanySystems;
Amit Roy 4
Perl Coding Guidelines
Wherever the variable name is not clear from the context, use {}.
Recommendation is to use scalar() where you are trying to get list size. This will improve
readability.
my $nListSize = scalar(@lIntList);
my $sHelpMessage = <<EOD;
Options:
-help Shows help
-file <path> Take options from file
EOD
Print $sHelpMessage;
Amit Roy 5
Perl Coding Guidelines
It is important to understand the process Perl goes through to test for truth.
First, if the value is not already a string, it is stringified. Strings remain as they
are.
If the string is "" or "0", it is considered as false.
This leads to the strange situation where the string "0.0" is TRUE.
But this is an unusual case. More commonly, confusion arises from the differences
between definedness, existence, and truth.
my $a = 0;
if ($a) { } # false
if (defined $a) { } # true
my %hash = (
a => 0,
b => 1,
c => 2
);
if ($hash{a}) { } # false because it is zero
if (exists $hash{d}) { } # false; no warning
if ($hash{d}) { } # false; produces warning with -w
Also note, you should use defined and exists where you are not sure enough about
the existence of the variable.
foreach (keys(%hNameAgeTable)) {
print; # means print $_
print $hNameAgeTable{$_};
}
while (<$fFile>) {
print;
}
Amit Roy 6
Perl Coding Guidelines
use Data::Dumper;
my $rStudentList = [
{
name => "joe",
roll => 2,
friendList => [
"martin",
"rob",
"pradip"
],
passYear => 1997
}
];
print Dumper($rStudentList);
Amit Roy 7
Perl Coding Guidelines
#!/bin/env perl
use 5.008; # check version
use strict;
use warnings;
use Getopt::Std;
## Global variables
my $gbExitOnError = 1;
## Main code
printBanner();
my $rCommandLineHash = parseCommandLine();
my $lFiles = readFiles($rCommandLineHash);
process($lFiles, $rCommandLineHash);
## Subroutine definitions
use Data::Dumper;
my $sName = Joe;
my @lNameList = qw(Martin Pradip Kaushik);
printAll($sName, @lNameList, \@lNameList);
sub printAll() {
print Dumper(@_);
}
$VAR1 = 'Joe';
$VAR2 = 'Martin'; # concatenated with @_
$VAR3 = 'Pradip'; # concatenated with @_
$VAR4 = 'Kaushik'; # concatenated with @_
$VAR5 = [ # can be isolated as list
'Martin',
'Pradip',
'Kaushik'
];
Amit Roy 8
Perl Coding Guidelines
# sub-routine use
mySub("x", [qw{1 2 3 4}], { x => 5, y => 6 }, 7); # ok
mySub(1, [1], { 1 => 1 }); # ok
mySub(1, 1, 1); # compile-time error
# do not use &mySub()
# sub-routine definition
sub mySub($@%;$) {
my ($sName, $pListRef, $pHashRef, $sOptArg) = @_;
print $sName."@$pListRef".$pHashRef->{$sName};
defined $sOptArg && print $sOptArg;
}
The benefit of using the Perl functions is that they are less platform dependent and it
is easier to trap errors.
Amit Roy 9
Perl Coding Guidelines
sub systemWrapper($) {
my $sCommand = shift;
my $nStatus = system($sCommand);
die System command failed \n if ($nStatus != 0);
}
systemWrapper(ls -1);
use FileHandle;
my $sFileName = qq{README.txt};
my $fFile = new FileHandle($sFileName);
die "Can't open file $sFileName ...\n" if (!defined $fFile);
while (my $sLine = <$fFile>) {
print $sLine;
}
# closes $fFile automatically
package MyXlsReader;
use strict;
use XlsCore;
# body
1;
#!/bin/env perl
use warnings;
use strict;
Amit Roy 10
Perl Coding Guidelines
use FileHandle;
Amit Roy 11