%%% $Id: perlCodeConventions.tex,v 1.48 2006-08-18 22:28:38 jhoblitt Exp $
\documentclass[panstarrs]{panstarrs}

\usepackage{verbatim}

% basic document variables
\title{Pan-STARRS Image Processing Pipeline}
\subtitle{Perl Code Standards}
\shorttitle{Perl Code Standards}
\author{Joshua Hoblitt}
\audience{Pan-STARRS PMO}
\group{Pan-STARRS Algorithm Group}
\project{Pan-STARRS Image Processing Pipeline}
\organization{Institute for Astronomy}
\version{DR02}
\docnumber{PSDC-430-013}

\begin{document}
\maketitle
\newcommand{\matchBracket}[1]{}         % help emacs match properly

% -- Revision History --
\RevisionsStart
% version     Date         Description
DR00& 2004-11-12 & First Draft\\
\hline
DR01& 2004-12-01 & Second Draft\\
\hline
DR02& 2005-01-24 & Third Draft\\
\RevisionsEnd

\textbf{\Large Referenced Documents}
\begin{center}
\begin{tabular}{|p{1in}|p{2.75in}|p{2.75in}|}
\hline
%%% References here.
\textbf{\PS{} ID} & \textbf{Title} & \textbf{Author} \\
\hline
430-004 &Pan-STARRS IPP C Code Standards    &Robert Lupton\\
\hline
\end{tabular}
\end{center}

\pagebreak
\tableofcontents

\pagebreak 
\pagenumbering{arabic}


%------------------------------------------------------------------------------

\section{Introduction}
\subsection{Ancestry}

This document is derived from the Pan-STARRS IPP C Code Standards document
(PSDC 430-004), which is derived from the Sun Microsystems Java language coding
standards presented in the \emph{Java Language Specification}\footnote{The
Java Language Specification -
\code{http://java.sun.com/docs/books/jls/index.html}}.

\begin{verbatim}
    Adapted with permission from
    CODE CONVENTIONS FOR THE JAVA^TM PROGRAMMING LANGUAGE.
    Copyright 1995-1999 Sun
    Microsystems, Inc.  All rights reserved.
\end{verbatim}

See the \emph{Java Code Conventions} web site\footnote{The Java Code
Conventions - \code{http://java.sun.com/docs/codeconv/}} for more details.

Such an adaption is explicitly permitted by the Sun Microsystems
copyright notice (Copyright.doc.html).

\subsection{Limitations}

Although Perl's syntax is similar to that of C or Java, there are many
signification deviations.  This has lead to a coding style within the Perl
community that is generally significantly different than that used for C or
Java (See the \code{perlstyle} Pod in the standard Perl documentation for an
example of this).  This document does not attempt to define the coding style
common with Perl programmers.  Instead, it is an attempt to make the C and Perl
coding styles as consistent as is reasonably feasible within the Pan-STARRS
project.  Further limiting the possible applicability of this document, only
language features that are deemed likely to be used by the Pan-STARRS project
are discussed.  This has resulted in only a brief discussion of Perl's
Object-Oriented features and none of it's more advanced features (e.g.
AUTOLOAD).

\subsection{Applicability}

This document is intended to be relevant to Perl5, version 5.8.0 or later.

\subsection{Conformance}

If any of the conventions established in this document conflict with source
code that has been formatted by \code{perltidy} (see \S\ref{perltidy}), the
formatting as output by \code{perltidy} will be considered to be in compliance
with the Perl Code Standards.

\subsection{To whom should I Complain?}

While Robert Lupton didn't actually write this document he would enjoy
receiving any complaints or comments it may generate.

\code{<rhl@astro.princeton.edu>}.


%------------------------------------------------------------------------------

\section{File Names}

This section lists commonly used file suffixes and names. 

\subsection{File Suffixes}

Software uses the following file suffixes (in lowercase):
\begin{center}
\begin{tabular}{ll}
\textbf{File Type}& \textbf{Suffix}\\
\hline
Perl scripts&               \code{.pl}\\
Perl modules&               \code{.pm}\\
Plain old documentation&    \code{.pod}\\
\end{tabular}
\end{center}

\subsection{Common File Names}

Frequently used file names include: 
\begin{center}
\begin{tabular}{lp{5in}}
\textbf{File Name}& \textbf{Use}\\
\hline
\file{Makefile.PL}&
The preferred name for a file that invokes a ``build'' process.  Typically this
calls \code{ExtUtils::MakeMaker} or \code{Module::Build} setup the the
necessary files to build and install a module or compile Swig generated C code.
\emph{The capitalized \code{.PL} suffix is reserved for build and configuration
scripts}\\
\end{tabular}
\end{center}


%------------------------------------------------------------------------------

\section{File Organization}

General rules:

\begin{itemize}
\item
A file consists of sections that should be separated by blank lines
and an optional comment identifying each section.

\item
Files longer than 1000 lines are cumbersome and should be avoided.

\item
For an example of a properly formatted program, see
\emph{Complete Program Example} (\S\ref{SourceExample}).

\item
``Scripts'' have user documentation included at the end of the file.

\item
``Modules'' have documentation included in a companion \code{.pod}.
\end{itemize}

\subsection{Source Files}
\subsubsection{Perl Scripts}

Script files should have, in the following order:

\begin{itemize}
\item 
A Bourne shell ``she-bang'' for \code{perl}.  e.g.  \code{#!/usr/bin/perl}.

\item 
A Copyright notice followed by a blank commented line.  Then one commented line
per CVS keyword to be expanded.

\item
An optional minimum \code{perl} version requirement in long form (vStrings are
not allowed).  Where \code(requirement = revision + version / 1000 + subversion
/ 1\_000\_000).  e.g. A minimum requirement of \code{perl} 5.8.5 would be
expressed as \code{use 5.008005}.

\item 
A \code{use strict} and \code{use warnings} declaration.

\item
An optional \code{$VERSION} declaration.  This is useful with
\code{Getopt::Long}'s \code{auto_version} feature.

\item 
Any modules to include. 

\item 
Any constant declarations. 

\item 
Any script level ``globals'' declared as lexical variables.  e.g. \code{my $foo}

\item
The functional ``body'' of the script.  This where command line parameter
parsing, subroutine calls, etc. are placed.

\item 
Any subroutines.

\item
A \code{__END__} token to instruct the \code{perl} parser to stop looking for
executable code.

\item
Any Pod documentation about the script.
\end{itemize}

For an example of a properly organized script, see \emph{Script File Example}
(\S\ref{foo.pl}).

\subsubsection{Perl Modules}

Module files should have, in the following order:

\begin{itemize}
\item 
A Copyright notice followed by a blank commented line.  Then one commented line
per CVS keyword to be expanded.

\item
A Perl \code{package} declaration.

\item
An optional minimum \code{perl} version requirement in long form (vStrings are
not allowed).  Where \code(requirement = revision + version / 1000 + subversion
/ 1\_000\_000).  e.g. A minimum requirement of \code{perl} 5.8.5 would be
expressed as \code{use 5.008005}.

\item 
A \code{use strict} and \code{use warnings} declaration.

\item
A \code{$VERSION} declaration.

\item 
Any ``base'' classes. 

\item 
Any modules to include. 

\item 
Any constant declarations. 

\item 
Any package variables.  e.g. \code{our $foo}

\item 
Any package scoped lexical variables.  e.g. \code{my $foo}

\item 
Any subroutines.

\item
A \code{1} on a line by itself so when the module is parsed it always ends with
a true expression.

\item
A \code{__END__} token to instruct the perl parser to stop looking for
executable code.

\end{itemize}

For an example of a properly organized module, see \emph{Module File Example}
(\S\ref{Foo.pm}).

\subsubsection{Plain Old Documentation}
\label{pod} 

Pod files that accompany a module should have the following order:

\begin{itemize}
\item
A \code{pod} command.

\item
A \code{NAME} section.

\item
A \code{SYNOPSIS} section.

\item
A \code{DESCRIPTION} section.

\item
A \code{USAGE} section.

\item
A \code{DEVELOPER NOTES} section.

\item
A \code{CREDITS} section.

\item
A \code{SUPPORT} section.

\item
A \code{AUTHOR} section.

\item
A \code{COPYRIGHT} section.

\item
A \code{SEE ALSO} section.

\item
A \code{cut} command.
\end{itemize}

For an example of a properly organized Pod, see \emph{Pod File Example}
(\S\ref{Foo.pod}).


%------------------------------------------------------------------------------

\section{Indentation}

Four spaces should be used as the unit of indentation; tabs are forbidden.

\subsection{Line Length}

Avoid lines longer than 110 characters.

When preparing documents, you should ensure that lines of this length
are not wrapped.  If you are using the standard PSDC \LaTeX{} class
file \file{panstarrs.cls}, \CODE|\begin{verbatim} ... \end{verbatim}|
will do this for you.

\subsection{Wrapping Lines}

When an expression will not fit on a single line, break it according
to these general principles:

\begin{itemize}
\item Break after a comma or operator.

\begin{verbatim}
    if ($a < $b ||
        $a > 2*$b) {
        $x = ($a + $b + $c) +
        sin($z);
    }
\end{verbatim}

\item Prefer higher-level breaks to lower-level breaks.

\item Indent new lines 1 indentation unit deeper than the nesting depth of the
line on which the expression began.

\item If it is convenient to list one statement per line (similar to a hash
declaration) place the closing parenthesis or brace on a new line.

\end{itemize}

Here are some examples of breaking subroutine calls:

\begin{verbatim}
    someSub(longExpression1, longExpression2, longExpression3, 
        longExpression4, longExpression5);
     
    $var = someSub(
        longExpression1,
        someSub(longExpression2, longExpression3)
    ); 
\end{verbatim}

Following are two examples of breaking an arithmetic expression. The first is
preferred, since the break occurs outside the parenthesized expression, which
is at a higher level.  The second is demonstrating a statement being broken at
too low a level.

\begin{verbatim}
    $longName1 = $longName2 * ($longName3 + $longName4 - $longName5) +
        4 * $longName6;                   # PREFER
    
    $longName1 = $longName2 * ($longName3 + $longName4 -
                           $longName5) + 4 * $longName6; # AVOID 
\end{verbatim}

Below are three acceptable ways to format ternary expressions.
\emph{Expression fragments should be indented such that \code{?} and \code{:}
are aligned vertically (as opposed to being indented a fixed number of
indentation units).}

\begin{verbatim}
    $alpha = (aLongBooleanExpression) ? $beta : $gamma;  

    $alpha = (aLongBooleanExpression) ? $beta
                                      : $gamma;  

    $alpha = (aLongBooleanExpression)
           ? $beta 
           : $gamma;  
\end{verbatim}


%------------------------------------------------------------------------------

\section{Comments}

\subsection{Deactivating Code}

Comments should not be used to comment out large sections of code.  When
deactivating 3 or fewer consecutive lines of code a double hash (\code{##})
should be used at the very beginning of the line(s).

Example of deactivating a single line code.

\begin{verbatim}
        if ($foo) {
    ##        print("foo");
        }
\end{verbatim}

When deactivating 4 or more lines of code an embedded Pod statement should be
used.  The opening statement should be \code{=for off} and the closing
statement should be \code{=cut}.  The deactivated section should remain nested
to the same depth as the surrounding code.

Example of deactivating multiple lines of code.

\begin{verbatim}
    =for off
    if ($foo) {
        print("foo");
    }
    =cut
\end{verbatim}

Example of temporarily reactivating disabled code.

\begin{verbatim}
    #=for off
    if ($foo) {
        print("foo");
    }
    =cut
\end{verbatim}

\subsection{Implementation Comments}

General rules:

\begin{itemize}
\item
Comments should be used to give overviews of code and provide additional
information that is not readily available in the code itself. Comments should
contain only information that is relevant to reading and understanding the
program. For example, information about how the corresponding package is built
or in what directory it resides should not be included as a comment.

\item
Discussion of nontrivial or non-obvious design decisions is appropriate, but
avoid duplicating information that is present in (and clear from) the code. It
is too easy for redundant comments to get out of date. In general, avoid any
comments that are likely to get out of date as the code evolves.

\item
Comments should not be enclosed in large boxes drawn with hashes or other
characters.

\item
Comments should never include special characters such as form-feed and
backspace.
\end{itemize}

\emph{The frequency of comments sometimes reflects poor quality of code. When
you feel compelled to add a comment, consider rewriting the code to make it
clearer.}

Programs can have three styles of implementation comments: single-line,
multi-line and trailing.

\subsubsection{Single-Line Comments}

Short comments can appear on a single line indented to the level of the code
that follows.  The comment should appear above the code that it is describing
and must have a space between the \code{#} and the first text.

Example of a single-line comment.

\begin{verbatim}
    # some words
\end{verbatim}

\subsubsection{Multi-Line Comments}

Merely a repetition of single-line comments.  Logically distinct but adjoining
comments should be separated by an empty comment line.

\begin{verbatim}
    # this is the start of a multi-line comment that continues across a couple of
    # lines, then has a logical separation before another comment
    #
    # this is an adjoined comment
\end{verbatim}

\subsubsection{Trailing Comments}
\label{col41} 

Very short comments can appear on the same line as the code they describe, and
should be indented to column 41\footnote{In emacs, this may be achieved with
\code{ESC;}}. If the code extends beyond this column, the comment should be
separated from the closing semi-colon by a single space.

Here's an example trailing comments:

\begin{verbatim}
    if ($a == 2) {
        return TRUE;                        # special case
    } else {
        return isPrime($a);                 # works only for odd a
    }
\end{verbatim}

\emph{\code{perltidy}(\S\ref{perltidy}) is incapable of formatting trailing
comments in this style.  It will force trailing comments to be 4 spaces to the
right of the last character in any statement on the line.  However, it will add
additional spaces to cause trailing comments in adjoining lines to be
vertically aligned.  Until such time as \code{perltidy} can following this
convention or a replacement tool is located, trailing comments as formatted by
\code{perltidy} will be considered acceptable.}

\subsection{API Comments}

Plain Old Documentation format or Pod will be used to produce documentation of
the subroutines and variables in the exposed API.  See \emph{Plain Old
Documentation} (\S\ref{pod}).

If you need to give information about an interface, or variable that isn't
appropriate for Podification, use a normal implementation single-line or
multi-line comment immediately \emph{before} the code (as exampled above).


%------------------------------------------------------------------------------

\section{Declarations}

\subsection{Lexical Variables}

One declaration per line with a single place between \code{my} and the identifier:

\begin{verbatim}
    my $level;                              # indentation level
    my $size;                               # size of table
\end{verbatim}

is preferred over:

\begin{verbatim}
    my ($level, $size);                     # AVOID!
\end{verbatim}

In almost all situations with the exception of when parameters are being passed
into a subroutine or variables are highly related \emph{and} the intent is
plainly obvious.  If there is any doubt as to the appropriate style to use
place one declaration per line.

\begin{verbatim}
    my ($verbose, $help);                   # Correct when the meaning is clear
    my ($foo, $bar) = @_;                   # Correct in a subroutine
\end{verbatim}

Do not combine different types in the same declaration.  Example:

\begin{verbatim}
    my ($foo, @fooArray);                   # AVOID!
\end{verbatim}

\subsubsection{Scalars}

Do not initialize more then one scalar per declaration.

\begin{verbatim}
    my $foo = \$bar;                        # Correct
    my ($foo, $bar) = (1, 2);               # AVOID!
\end{verbatim}

\subsubsection{Arrays}

When assigning a large number of elements to an array a single column table
format should be used.

\begin{verbatim}
    my @foo = (1, 'two', 3);                # Correct

    my @foo = (                             # Correct
        1,
        'two',
        3,
        'four',
        5,
        'six',
        7,
        'eight',
        9,
        'ten'
    );

    my @foo = (1, 'two', 3, 'four', 5, 'six', ...   # AVOID!
\end{verbatim}

Consider using the \code{qw} operator to avoid repetitive string quoting when
assigning to an array.

\begin{verbatim}
    my @foo = qw( 1 two 3 );

    my @foo = qw(
        1
        two
        3
        four
        5
        six
    );
\end{verbatim}

\subsubsection{Hashes}

When assigning a large number of elements to a hash a double column table
format should be used.

\begin{verbatim}
    my %foo = (one => 1, two => 2);     # Correct

    my %foo = (                         # Correct
        one   => 1,
        two   => 2,
        three => 3,
        four  => 4,
        five  => 5,
        six   => 6,
        seven => 7,
        eight => 8,
        nine  => 9,
        ten   => 10
    );

    my %foo = (one => 1, two => 2, three => 3, ...  # AVOID!
\end{verbatim}

\subsection{Local Variables}

Avoid \code{local} declarations that hide user declared variables from higher
level scopes. For example, do not declare the same variable name in an inner
block:

\begin{verbatim}
    my $count;
    ...
    sub mySubroutine
    {
        local $count;                       # AVOID!
        ...
    }
\end{verbatim}

\emph{This restriction does not apply to Perl's built-in variables or the
package variable used by some modules to control global behavior.}

\subsection{Package Variables}

See \emph{When to Make Symbols Global} (\S\ref{globals}).

\subsection{Initialization}

General rules:

\begin{itemize}
\item
Try to initialize local variables where they're declared.

\item
Do not initialize variables with an empty string or list; this is pointless.

\item
A reason not to initialize a variable where it's declared is if the initial
value depends on some computation occurring first.

\item
In some cases it may be necessary to initialize a variable to suppress a
compiler warning; in this case a comment should explain the circumstances.
\end{itemize}

\subsection{Placement}

Variables should ordinarily be declared at the top of the block in
which they appear, unless there is some reason to declare them later.
This allows them to be initialized as they are created, and naturally
associates their declaration with their use.

Practical examples of when \emph{not} to place variable declarations at the top
of a block include loop iterators, intermediate value variables, and
variables used for returning values from nested scopes.

\subsection{Subroutine Declarations}

When coding subroutines the following formatting rules should be
followed:

\begin{itemize}
\item 
Subroutine declarations may be preceded by a short comment describing what the
subroutine does.  These comments should include a brief description as well as
other warnings, bugs, etc. as needed.

\item
The subroutine body's open brace \CODE.{. should be in column 1 of the next
line.

\item
The first line after the opening brace should declare a list of lexical
variables for input parameters and assign \code{shift} or \code{@_} to it.

\item
Closing brace \CODE.}. starts a line by itself.

\item
The last line before the closing brace must explicitly declare a return value.

\item
Do not directly use the \code{@_} array.

\item
Do not nest named subroutines.
\end{itemize}

\begin{verbatim}
    sub subName                         # Correct
    {
        my $param = shift;
        ...
        return $val;
    }

    sub subName                         # Correct
    {
        my ($param1, $param2, ...) = @_;
        ...
        return $val;
    }

    sub subName                         # AVOID!
    {
        if ($_[0] eq "foo") {
        ...
    }
\end{verbatim}


%------------------------------------------------------------------------------

\section{Statements}
\subsection{Simple Statements}

Each line should usually contain only one statement. Example:

\begin{verbatim}
    $x = sqrt($x2);                         # Correct
    $i++;                                   # Correct  
    $x = sqrt($x2); $i++;                   # AVOID!
\end{verbatim}

An example of a reasonable two-statement line is:

\begin{verbatim}
    $foo++; $bar--;
\end{verbatim}

where the two actions are intimately related.

\subsubsection{return Statements}

A \code{return} statement should not use parentheses unless they make the
return value more obvious in some way.  All subroutines must have an explicit,
non-null, return statement unless they are returning an error condition, in
which case a bare \code{return} is acceptable.   Example:

\begin{verbatim}
    return $a;                              # Correct
    return;                                 # Correct only if indicating an error
    return $myDisk->size;                   # Correct
    return ($size ? $size : $defaultSize);  # Correct
    return($a);                             # AVOID!
    return ($a);                            # AVOID!
\end{verbatim}

\emph{In the absence of an explicit return statement Perl will return the
results of the last statement executed.  Relying on this behavior is likely to
confuse maintenance programmers and therefore should be avoided.}

Try to make the structure of your program match the intent. Example:

\begin{verbatim}
    if (booleanExpression) {
        return true;
    } else {
        return false;
    }
\end{verbatim}

should instead be written as

\begin{verbatim}
    return booleanExpression;
\end{verbatim}

If you're concerned that the reader may not know that \code{booleanExpression}
is boolean, use:

\begin{verbatim}
    return (booleanExpression ? true : false);
\end{verbatim}

Similarly,

\begin{verbatim}
    if (condition) {
        return $x;
    }
    return $y;
\end{verbatim}

should be written as

\begin{verbatim}
    return (condition ? x : y);
\end{verbatim}

\subsection{Compound Statements}

Compound statements are statements that contain lists of statements enclosed in
braces. See the following sections for examples.

\begin{itemize}
\item The enclosed statements should be indented one more level than the compound statement.

\item The opening brace should be at the end of the line that begins
the compound statement; the closing brace should begin a line and be
indented to the beginning of the compound statement.
\end{itemize}

\subsubsection{if, if-else, if-elsif-else Statements}

The \code{if-else} class of statements should have the following form:

\begin{verbatim}
    if (condition) {
        statements;
    }

    if (condition) {
        statements;
    } else {
        statements;
    }

    if (condition) {
        statements;
    } elsif (condition) {
        statements;
    } else {
        statements;
    }
\end{verbatim}

\emph{The same formatting applies to \code{unless}, \code{unless-else}, \&
\code{unless-elsif-else} statements.}

\subsubsection{C style for Statements}

A \code{for} statement should have the following form:

\begin{verbatim}
    for (initialization; condition; update) {
        statements;
    }
\end{verbatim}

For example:

\begin{verbatim}
    for (my $i = 0; $i < 100; $i++) {
        print "$i\n";
    }
\end{verbatim}

An empty \code{for} statement (one in which all the work is done in the
initialization, condition, and update clauses) should have the following form:

\begin{verbatim}
    for (initialization; condition; update) {}
\end{verbatim}

When using the comma operator in the initialization or update clause
of a \code{for} statement, avoid the complexity of using more
than three variables. If needed, use separate statements before the
\code{for} loop (for the initialization clause) or at the end of
the loop (for the update clause).

\emph{Generally, ``Perlish'' style loops are preferred over the C form.}

\subsubsection{Perl style for, foreach Statements}

A Perlish \code{for} or \code{foreach} statement should have the following
form:

\begin{verbatim}
    foreach my $item (@workingList) {
        statements;
    }

    foreach my $item (@workingList) {
        statements;
    } continue {
        statements;
    }
\end{verbatim}

The current working item should be interacted with through a declared lexical
variable and not via \code{$_}.

\begin{verbatim}
    foreach (@workingList) {                # AVOID!
        # do stuff with $_
    }
\end{verbatim}

\subsubsection{while Statements}

A \code{while} statement should have the following form:

\begin{verbatim}
    while (condition) {
        statements;
    }

    while (condition) {
        statements;
    } continue {
        statements;
    }
\end{verbatim}

Do \emph{not} use \code{$_} when iterating through a filehandle.  Instead, place
each ``line'' of the filehandle into a named lexical variable.

\begin{verbatim}
    my $line;
    while (defined($line = <FILE>)) {
        statements;
    }
\end{verbatim}

An empty \code{while} statement should have the following form:

\begin{verbatim}
    while (condition) {}
\end{verbatim}

\emph{Consider using the \code{map} subroutine instead of a loop for list
generation.}

\subsubsection{do Statements}

In Perl \code{do} is a built-in subroutine.  Traditional \code{do-while} like
statements may be constructed with it by using Statement Modifiers (see
\S\ref{statement-modifiers}) in the following form:

\begin{verbatim}
    do {
        statements;
    } statement-modifier (condition);
\end{verbatim}

\subsubsection{Label Statements}

Code labels should be indented to align with the previous level of indentation.
Do \emph{not} label a loop unless you are going to use the label.

\begin{verbatim}
    MYLABEL: while (condition) {
        if (condition) {
            next MYLABEL;
        }
    }
\end{verbatim}

\subsubsection{Blocks}

The contents of a block should be indented one level.

\begin{verbatim}
    $foo = foobar($baz);
    {
        my $bat = fooBaz();
        ...
    }
\end{verbatim}

\subsection{Statement Modifiers}
\label{statement-modifiers}

These keywords are considered acceptable for use as ``Statement Modifiers'':
\code{if}, \code{unless} \& \code{until}.  These keywords should generally be
avoided for that purpose: \code{while} \& \code{foreach}.

Statement Modifiers should only be used \emph{only} when it makes the intent
for the code more obvious.  e.g.

\begin{verbatim}
    die "you forgot to handle some case" unless $flag;  # Correct
    $a = 1 if (($b == $c) && defined($d);               # AVOID!
\end{verbatim}

Parenthesis should be used with complex expressions.

\begin{verbatim}
    someSubCall($a, $b, $c) if ($foo eq 'bar' || $baz > 10);    # Correct
    someSubCall($a, $b, $c) if $foo eq 'bar' || $baz > 10;      # AVOID!
\end{verbatim}


%------------------------------------------------------------------------------

\section{White Space}

In general, be very liberal in the use of whitespace, both horizontal and
vertical, if it will improve the clarity and readability of your code.

\subsection{Blank Lines}

Blank lines improve readability by setting off sections of code that
are logically related.

Two blank lines should always be used between sections of a source file.

One blank line should always be used in the following circumstances:

\begin{itemize}
\item
Between the local variables in a subroutine and its first statement

\item
Between logical sections inside a subroutine to improve readability
\end{itemize}

\subsection{Blank Spaces}

Blank spaces should be used in the following circumstances:
\begin{itemize}
\item
A keyword followed by a parenthesis should be separated by a space. Example:

\begin{verbatim}
    while (true) {
        ...
    }
\end{verbatim}

\emph{A blank space should not be used between a subroutine name and its
opening parenthesis. This helps to distinguish keywords from subroutine calls.}

\item
A blank space should appear after commas in parameter lists.

\begin{verbatim}
    subName(1, 2, 3);
\end{verbatim}

\item
Binary operators should be separated from their operands by spaces.  Blank
spaces should never separate unary operators such as a unary minus, increment
(\code{++}), and decrement (\code{--}) from their operands. Examples:

\begin{verbatim}
    $a += $c + $d;
    $a = ($a + $b) / ($c * $d);

    while ($d++ = $s++) {
        $n++;
    }
    printf("size is %d\n", $foo);
\end{verbatim}

\item
The expressions in a \code{for} statement should be separated by blank spaces.
Example:

\begin{verbatim}
    for (expr1; expr2; expr3) {}
\end{verbatim}

\item
Built-in quoting functions should have spaces between their parameters and the
opening/closing delimiters.

\begin{verbatim}
    my @things = qw( foo bar baz );
\end{verbatim}
\end{itemize}

Blank spaces should \emph{not} be used in the following circumstances:

\begin{itemize}
\item
A variable dereference or method call should not have any blank spaces around
the \code{->} operator.

\begin{verbatim}
    $myHashRef->{'foo'};
    $myObject->foo;
\end{verbatim}

\end{itemize}


%------------------------------------------------------------------------------

\section{Naming Conventions}

Naming conventions make programs more understandable by making them easier to
read. They can also give information about the subroutine of the identifier --
for example, whether it's a constant or a subroutine -- which can be helpful in
understanding the code.  Remember these are guidelines for improving
readability; clarity should trump rigid adherence to the guideline.
 
{ \small 
\begin{tabular}{lp{3in}p{3in}}
\textbf{Identifier Type} &
\textbf{Rules for Naming} &
\textbf{Examples} \\
\hline\\

Script Files &

The filenames of all scripts should be verbal phrases, in mixed case.  The
capitalized \code{.PL} suffix is reserved for build and configuration scripts.

&

\code{foo.pl}\hfil\break
\code{fooBar.pl}\hfil\break
\code{Makefile.PL}\hfil\break

\\

Module Files &

The filenames of all modules should be verbal phrases, in mixed case, with the
first letter capitalized.

&

\code{Foo.pm}\hfil\break
\code{FooBar.pm}\hfil\break

\\

Pod Files &

The filenames of all stand-alone Pod should follow the same rules as module
files.

&

\code{Foo.pod}\hfil\break
\code{FooBar.pod}\hfil\break

\\

Subroutines &

The names of all public subroutines (and methods) should be verbal phrases, in
mixed case.

Private subroutines (and methods) should follow the same rules as public
subroutines but be prefixed with an underscore.

&

\code{run();}\hfil\break
\code{runFast();}\hfil\break
\code{getBackground();}\hfil\break
\code{_keepHandsOff();}\hfil\break

\\

Variables &

Variable names should be in mixed case and be short yet meaningful. The choice
of a variable name should be mnemonic- that is, designed to indicate to the
casual observer the intent of its use. One-character variable names should be
avoided except for temporary \emph{throwaway} variables. Common names for
temporary variables are \code{$i}, \code{$j}, \code{$k}, \code{$m}, and \code{$n}
for integers; \code{$c}, \code{$d}, and \code{$e} for characters.

&

\code{$i;}\hfil\break
\code{$i;}\hfil\break
\code{$c;}\hfil\break
\code{$myWidth;}\hfil\break
\code{$pseudo;}\hfil\break
\code{$myFiddleFactor;}\hfil\break

\\
 
Constants &

Constant names should be in all capital letters and highly descriptive.

&
\code{use constant PI => 3.14159265;}\hfil\break
\code{use constant LENGTHS => qw( 2, 4, 8 );}\hfil\break
\code{use constant CLASSES => {a => 1, b => 2};}\hfil\break

\\

Namespaces &

Must start with a capitalized letter but otherwise follow the same naming
conventions as variables.

&

\code{package PS::IPP::Metadata;}\hfil\break
\code{package PS::IPP::Modules::Debias;}\hfil\break
\code{package PS::MOPS::DB::Detections;}\hfil\break
\code{package PS::MOPS::Util::MPC;}\hfil\break

\\

Labels &

Label names should be in all capital letters and short.  Generally they should
attempt to describe the `thing' being operated on by the loop they are labeling.

&

\code{LINE:}\hfil\break
\code{CONNECTION:}\hfil\break
\code{IMAGE:}\hfil\break

\\

\end{tabular}
}


%------------------------------------------------------------------------------

\section{Programming Practices}

\subsection{When to Make Symbols Global}
\label{globals}

Only declare variables as package variables (\code{our}) if they are intended
to be visible outside of the current namespace.  All other variables within a
namespace should be declared as lexical.

\begin{verbatim}
    our $VERSION = '1.00';                  # Correct
    our $localCounter;                      # AVOID! - should be lexical

    use base qw( Exporter );
    our @EXPORT_OK = qw( $foo $bar );       # Correct
\end{verbatim}

\subsection{Constants}

Numerical constants (literals) should not be coded directly, except for
small integers such as -1, 0, and 1 which are permitted to e.g. appear
in a \code{for} loop as counter values.  

The \code{constant} pragma should be used to declare constants.
\emph{``constants'' created this way can not be interpolated inside of double
quoted strings.}

See the \code{constant} module's Pod for further details.

\subsection{Variable Assignments}

Avoid assigning several variables to the same value in a single
statement, unless the variables are intimately related. Acceptable examples:

\begin{verbatim}
    $row0 = $col0 = 0;
    $sum = $sumx = $sumy = 0;
\end{verbatim}

Do not use the assignment operator in a place where it can be easily confused
with the equality operator. Example:

\begin{verbatim}
    if ($c++ = $d++) {                      # AVOID!
        ...
    }
\end{verbatim}

should be written as:

\begin{verbatim}
    if (($c++ = $d++) != 0) {
        ...
    }
\end{verbatim}

Do not use embedded assignments in an attempt to improve run-time
performance. This is the job of the compiler. Example:

\begin{verbatim}
    $d = ($a = $b + $c) + $r;               # AVOID!
\end{verbatim}

should be written as

\begin{verbatim}
    $a = $b + $c;
    $d = $a + $r;
\end{verbatim}

\subsection{Miscellaneous Practices}
\subsubsection{Parentheses}

It is generally a good idea to use parentheses liberally in
expressions involving mixed operators to avoid operator precedence
problems. Even if the operator precedence seems clear to you, it might
not be to others-you shouldn't assume that other programmers know
precedence as well as you do. In cases where the precedence rules
are clear, the parentheses may be omitted.

\begin{verbatim}
    if ($a & $b || $c & $d) {}              # AVOID!
    if (($a & $b) || ($c & $d)) {}          # Correct
\end{verbatim}

In particular, expressions involving the combinations of \code{||} and
\code{&&} should be fully parenthesized, as should all expressions containing
bitwise operators:

\begin{verbatim}
    if (($a == $b && $c == $d) || $e == $f) {}
    $l << ($j + $k)
    ($l << $j) + $k
    ($i & $b) | $c
\end{verbatim}

\subsubsection{Expressions before `?' in the Conditional Operator }

If an expression containing a binary operator appears before the \code{?} in
the ternary \code{?:} operator, it should be parenthesized. Example:

\begin{verbatim}
    ($x >= 0) ? $x : -$x;
\end{verbatim}

\subsubsection{\$\_}

Use of the ``default'' variable (\code{$_}) should be avoided.

\begin{verbatim}
    my $foo =~ /(foo.*)/;                   # Correct
    foreach my $foo (@bar) {}               # Correct
    /(foo.*)/;                              # AVOID!
    $_ = ~/(foo.*)/;                        # AVOID!
\end{verbatim}

\subsubsection{Filehandles}

Do not use ``bare-words'' as filehandles except for \code{STDIN}, \code{STDOUT},
and \code{STDERR}.

\begin{verbatim}
    open(STDOUT, '>', $foo) or die "can not open STDOUT: $!";       # Correct
    open(my $fh, '>', $foo) or die "can not open file $foo: $!";    # Correct
    open(FILE, '>', $foo) or die "can not open file $foo: $!";      # AVOID!
\end{verbatim}

\subsubsection{System Calls}

Always check the return code of system calls.

\begin{verbatim}
    open(my $fh, '>', $foo) or die "can not open file $foo: $!";    # Correct
    close($fh) or die "can not close file $foo: $!";                # Correct
    chdir($foo);                                                    # AVOID!
\end{verbatim}

\subsubsection{Chop vs. Chomp}

Do not use \code{chop} to remove newline characters as it will remove any
character (newline or not).

\begin{verbatim}
    my $foo = "baz\n";                  # string with newline
    chomp($foo);                        # removes "\n" - Correct
    chomp($foo);                        # chomping the same string twice is safe
    chop($foo);                         # removes "z" - AVOID!
\end{verbatim}

\subsubsection{Array Subscripts}

Use ``cuddled'' brackets \code{[]} when accessing an array element.

\begin{verbatim}
    $foo[-1];                           # Correct
    (someSub($foo))[1];                 # Correct
    $foo[ 6 ];                          # AVOID!
\end{verbatim}

\subsubsection{Hash Subscripts}

Use ``cuddled'' brackets \CODE.{}. when accessing a hash element.  It is
acceptable to use ``bare-words'' as a hash key (\emph{this rule may be subject
to change}).

\begin{verbatim}
    $foo{bar};                          # Correct
    $foo{$baz};                         # Correct
    $foo{'fiddle'};                     # Correct
    $foo{ lish };                       # AVOID!
    $foo{ 'zab' };                      # AVOID!
\end{verbatim}

\subsubsection{Loading Modules}

Modules may be loaded with an optional version requirement.  This is
particularly useful for modules that exist in the Perl core but have newer
versions available on CPAN.

\begin{verbatim}
    use Foo;                            # Correct
    use Foo 0.02;                       # Correct
\end{verbatim}

Do not use \code{require} to prevent a module from exporting symbols into the
caller's namespace.  Instead, provide \code{use} with an empty parameter list.

\begin{verbatim}
    use Foo qw();                       # Correct
    use Foo ();                         # Correct
    require Foo;                        # AVOID!
\end{verbatim}

This also works with a minimum module version requirement.

\begin{verbatim}
    use Foo 0.02 qw();                  # Correct
\end{verbatim}

\subsubsection{Inheritance}

Do not use the \code{@ISA} package variable for sub-classing.  Instead, use the
\code{base} pragma.

\begin{verbatim}
    use base qw( Foo );                 # Correct
    our @ISA = qw( Foo );               # AVOID!
\end{verbatim}

\subsubsection{Calling Subroutines}

Do not use the \code{&} sigil to to disambiguate a subroutine from a
``bare-word''.  Instead, use empty parentheses adjoined to the subroutine call.

\emph{Only use the \code{subs} pragma as a last resort.}

\begin{verbatim}
    fooBar($foo);                       # Correct
    fooBar();                           # Correct
    &fooBar;                            # AVOID!
    &fooBar();                          # AVOID!
    use subs qw( fooBar );              # last resort - Correct
\end{verbatim}

\subsubsection{Calling Methods}

Leave the parentheses off method calls that aren't being passed parameters.

\begin{verbatim}
    $myObj->fooBar;                     # Correct
    $myObj->fooBar($foo);               # Correct
    $myObj->fooBar();                   # AVOID!
\end{verbatim}

\subsubsection{Quoting Strings}

\begin{itemize}
\item
Unless variable interpolation needs to occur inside of a string or is likely to
be needed in the future, use single quotes \code{''} instead of double quotes
\code{""}.

\item
When possible use \code{END} as the termination token for ``\code{<<HERE}
docs''.

\begin{verbatim}
    my $string = <<END
    foo bar
    bat baz
    END
\end{verbatim}

\item
Try to use the \code{qw} operator whenever possible.

\item
 Consider using the \code{q} and \code{qq} operators instead of backslashes
(\code{\}) when quoting strings that contain other quotes or backslashes.

\item
Consider using the \code{quotemeta} subroutine when handling strings that
contain meta-characters.  \end{itemize}

\subsubsection{String Concatenation}

Avoid use of the string concatenation operator (\code{.}) where it's
unnecessary.

\begin{verbatim}
    $foo = "foo" . "bar";               # Correct
    $foo .= "bar";                      # Correct
    print "foo" , "bar";                # Correct
    print "foo" . "bar";                # AVOID!
\end{verbatim}

\subsubsection{Regular Expressions}

Use the ``extended'' regular expression syntax whenever practical.

\begin{verbatim}
    qr/^                                # Correct
       ( -? (?:Bork\s*){0,9} , (?:Bork\s*){0,9}
          , (?:Bork\s*){0,9} , (?:Bork\s*){0,9} )
        - ( (?:Bork\s*){0,9} , (?:Bork\s*){0,9} )
        - ( (?:Bork\s*){0,9} , (?:Bork\s*){0,9} )
        T ( (?:Bork\s*){0,9} , (?:Bork\s*){0,9} )
        : ( (?:Bork\s*){0,9} , (?:Bork\s*){0,9} )
        : ( (?:Bork\s*){0,9} , (?:Bork\s*){0,9} )
    $/ix;

    qr/^(-?(?:Bork\s*){0,9},(?:Bork\s*){0,9},(?:Bork\s*){0,9},...$/i # AVOID!
\end{verbatim}

\subsubsection{Subroutine Prototypes}

Do not use subroutine prototypes.  If you need to validate subroutine
parameters see \code{Params::Validate} (\S\ref{Params::Validate}).

\begin{verbatim}
    sub myopen (*;$);                   # AVOID!
    sub myopen (*;$) { }                # AVOID!
\end{verbatim}


%------------------------------------------------------------------------------
\appendix				%Begin Appendices
%------------------------------------------------------------------------------

\section{Code Examples}
\subsection{Script File Example}
\label{foo.pl} 

\verbatiminput{perlCodeExamples/foo.pl}

\subsection{Module File Example}
\label{Foo.pm} 

\verbatiminput{perlCodeExamples/Foo.pm}

\subsection{Pod File Example}
\label{Foo.pod} 

\verbatiminput{perlCodeExamples/Foo.pod}

\subsection{Complete Program Example}
\label{SourceExample} 

An example of \file{buildIndex.pl} that conforms with the Perl code
convention.

\verbatiminput{perlCodeExamples/buildIndex.pl}


%------------------------------------------------------------------------------

\section{How to Achieve This Style with Perltidy}
\label{perltidy}

\code{pertidy} is a Perl specific code ``beautifier'' with functionality
similar to \code{indent} or \code{astyle}.  It is freely available from
\code{http://perltidy.sourceforge.net/}.

\code{pertidy} can be configured with either command line switches or a
\file{.perltidyrc} file in your home directory.  Detailed instructions on how
to configure \code{perltidy} can be found in it's manpage\footnote{Perltidy
manpage - http://perltidy.sourceforge.net/perltidy.html}

Example \file{.perltidyrc} file to achieve the Perl code convention:

\verbatiminput{perlCodeExamples/.perltidyrc}


%------------------------------------------------------------------------------

\section{Params::Validate}
\label{Params::Validate} 

\code{Params::Validate}\footnote{Params::Validate -
http://search.cpan.org/~drolsky/Params-Validate/} is a Perl module that allows
you to perform rigorous subroutine parameter validation.  It is highly
configurable and validation may be deactivated at runtime.

The basic premise is that a validation specification is passed to one of
several ``validating'' subroutines along with the parameters the subroutine was
called with.

An example \code{Params::Validate} named parameters validation spec taken from
the \code{HTTP::Range}\footnote{HTTP::Range -
http://search.cpan.org/~jhoblitt/HTTP-Range/} module.

\begin{verbatim}
    my %args = validate( @_,
        {
            request => {
                type        => OBJECT,
                isa         => 'HTTP::Request',
            },
            length => {
                type        => SCALAR,
                callbacks   => {
                    'length is > 0'         => sub { $_[0] > 0 },
                    'length is + integer'   => sub { $_[0] =~ /^\d+$/ },
                },
            },
            segments => {
                type        => SCALAR,
                default     => 4,
                callbacks   => {
                    'segments is > 1'       => sub { $_[0] > 1 },
                    'segments is + integer' => sub { $_[0] =~ /^\d+$/ },
                    'segments is <= length' => sub { $_[0] <= $_[1]->{ 'length' } },
                },
            },
        },
    );

\end{verbatim}

Please see the \code{Params::Validate} Pod\footnote{Params::Validate Pod -
http://search.cpan.org/~drolsky/Params-Validate/lib/Params/Validate.pm} for
further details.


%------------------------------------------------------------------------------

\bibliographystyle{plain}
\bibliography{panstarrs}

\end{document}
