Subroutines / Prohibit Builtin Homonyms --------------------------------------- Common sense dictates that you shouldn't declare subroutines with the same name as one of Perl's built-in functions. See `perldoc perlfunc' for a list of built-ins. sub open {} #not ok sub exit {} #not ok sub print {} #not ok #You get the idea... Subroutines / Prohibit Excess Complexity ---------------------------------------- All else being equal, complicated code is more error-prone and more expensive to maintain than simpler code. The first step towards managing complexity is to establish formal complexity metrics. One such metric is the McCabe score, which describes the number of possible paths through a subroutine. This Policy approximates the McCabe score by summing the number of conditional statements and operators within a subroutine. Research has shown that a McCabe score higher than 20 is a sign of high-risk, potentially untestable code. See http://www.sei.cmu.edu/str/descriptions/cyclomatic_body.html for some discussion about the McCabe number and other complexity metrics. The usual prescription for reducing complexity is to refactor code into smaller subroutines. Mark Dominus book "Higher Order Perl" also describes callbacks, recursion, memoization, iterators, and other techniques that help create simple and extensible Perl code. Subroutines / Prohibit Explicit Return Undef -------------------------------------------- Returning `undef' upon failure from a subroutine is pretty common. But if the subroutine is called in list context, an explicit `return undef;' statement will return a one-element list containing `(undef)'. Now if that list is subsequently put in a boolean context to test for failure, then it evaluates to true. But you probably wanted it to be false. sub read_file { my $file = shift; -f $file || return undef; #file doesn't exist! #Continue reading file... } #and later... if ( my @data = read_file($filename) ){ # if $filename doesn't exist, # @data will be (undef), # but I'll still be in here! process(@data); } else{ # This is my error handling code. # I probably want to be in here # if $filname doesn't exist. die "$filename not found"; } The solution is to just use a bare `return' statement whenever you want to return failure. In list context, Perl will then give you an empty list (which is false), and `undef' in scalar context (which is also false). sub read_file { my $file = shift; -f $file || return; #DWIM! #Continue reading file... } Subroutines / Protect Private Subs ---------------------------------- By convention Perl authors (like authors in many other languages) indicate private methods and variables by inserting a leading underscore before the identifier. This policy catches attempts to access private variables from outside the package itself. Subroutines / Prohibit Ampersand Sigils --------------------------------------- Since Perl 5, the ampersand sigil is completely optional when invoking subroutines. And it's easily confused with the bitwise 'and' operator. @result = &some_function(); #Not ok @result = some_function(); #ok Subroutines / Prohibit Subroutine Prototypes -------------------------------------------- Contrary to common belief, subroutine prototypes do not enable compile-time checks for proper arguments. Don't use them. Subroutines / Require Final Return ---------------------------------- Subroutines without explicit return statements at their ends can be confusing. It can be challenging to deduce what the return value will be. Furthermore, if the programmer did not mean for there to be a significant return value, and omits a return statement, some of the subroutine's inner data can leak to the outside. Consider this case: package Password; # every time the user guesses the password wrong, it's value # is rotated by one character my $password; sub set_password { $password = shift; } sub check_password { my $guess = shift; if ($guess eq $password) { unlock_secrets(); } else { $password = (substr $password, 1).(substr $password, 0, 1); } } 1; In this case, the last statement in check_password() is the assignment. The result of that assignment is the implicit return value, so a wrong guess returns the right password! Adding a `return;' at the end of that subroutine solves the problem. The only exception allowed is an empty subroutine. Input Output / Prohibit Backtick Operators ------------------------------------------ Backticks are super-convenient, especially for CGI programs, but I find that they make a lot of noise by filling up STDERR with messages when they fail. I think its better to use IPC::Open3 to trap all the output and let the application decide what to do with it. use IPC::Open3; @output = `some_command`; #not ok my ($writer, $reader, $err); open3($writer, $reader, $err, 'some_command'); #ok; @output = <$reader>; #Output here @errors = <$err>; #Errors here, instead of the console Input Output / Prohibit Two Arg Open ------------------------------------ The three-argument form of `open' (introduced in Perl 5.6) prevents subtle bugs that occur when the filename starts with funny characters like '>' or '<'. The the IO::File manpage module provides a nice object-oriented interface to filehandles, which I think is more elegant anyway. open( $fh, '>output.txt' ); # not ok open( $fh, q{>}, 'output.txt ); # ok use IO::File; my $fh = IO::File->new( 'output.txt', q{>} ); # even better! Input Output / Prohibit One Arg Select -------------------------------------- Conway discourages the use of a raw `select()' when setting autoflushes. We'll extend that further by simply prohibiting the one-argument form of `select()' entirely; if you really need it you should know when/where/why that is. For performing autoflushes, Conway recommends the use of `IO::Handle' instead. select((select($fh), $|=1)[0]); # not ok select $fh; # not ok use IO::Handle; $fh->autoflush(); # ok *STDOUT->autoflush(); # ok Input Output / Require Braced File Handle With Print ---------------------------------------------------- The `print' function has a unique syntax that supports an optional file handle argument. Conway suggests wrapping this argument in braces to make it visually stand out from the other arguments. When you put braces around any of the special package-level file handles like `STDOUT', `STDERR', and `DATA', you must the `'*'' sigil or else it won't compile under `use strict 'subs''. print $FH "Mary had a little lamb\n"; #not ok print {$FH} "Mary had a little lamb\n"; #ok print STDERR $foo, $bar, $baz; #not ok print {STDERR} $foo, $bar, $baz; #won't compile under 'strict' print {*STDERR} $foo, $bar, $baz; #perfect! Input Output / Prohibit Bareword File Handles --------------------------------------------- Using bareword symbols to refer to file handles is particularly evil because they are global, and you have no idea if that symbol already points to some other file handle. You can mitigate some of that risk by `local'izing the symbol first, but that's pretty ugly. Since Perl 5.6, you can use an undefined scalar variable as a lexical reference to an anonymous filehandle. Alternatively, see the the IO::Handle manpage or the IO::File manpage or the FileHandle manpage modules for an object-oriented approach. open FH, '<', $some_file; #not ok open my $fh, '<', $some_file; #ok my $fh = IO::File->new($some_file); #ok Input Output / Prohibit Readline In For Loop -------------------------------------------- Using the readline operator in a `for' or `foreach' loop is very inefficient. The iteration list of the loop creates a list context, which causes the readline operator to read the entire input stream before iteration even starts. Instead, just use a `while' loop, which only reads one line at a time. for my $line ( <$file_handle> ){ do_something($line) } #not ok while ( my $line = <$file_handle> ){ do_something($line) } #ok Testing And Debugging / Prohibit No Warnings -------------------------------------------- There are good reasons for disabling certain kinds of warnings. But if you were wise enough to `use warnings' in the first place, then it doesn't make sense to disable them completely. By default, any `no warnings' statement will violate this policy. However, you can configure this Policy to allow certain types of warnings to be disabled (See the Configuration manpage). A bare `no warnings' statement will always raise a violation. Testing And Debugging / Require Use Warnings -------------------------------------------- Using warnings is probably the single most effective way to improve the quality of your code. This policy requires that the `'use warnings'' statement must come before any other statements except `package', `require', and other `use' statements. Thus, all the code in the entire package will be affected. Testing And Debugging / Prohibit No Strict ------------------------------------------ There are good reasons for disabling certain kinds of strictures, But if you were wise enough to `use strict' in the first place, then it doesn't make sense to disable it completely. By default, any `no strict' statement will violate this policy. However, you can configure this Policy to allow certain types of strictures to be disabled (See the Configuration manpage). A bare `no strict' statement will always raise a violation. Testing And Debugging / Require Use Strict ------------------------------------------ Using strictures is probably the single most effective way to improve the quality of your code. This policy requires that the `'use strict'' statement must come before any other statements except `package', `require', and other `use' statements. Thus, all the code in the entire package will be affected. Builtin Functions / Prohibit Sleep Via Select --------------------------------------------- Conway discourages the use of `select()' for performing non-integer sleeps. Although its documented in the perlfunc manpage, its something that generally requires the reader to RTFM to figure out what `select()' is supposed to be doing. Instead, Conway recommends that you use the `Time::HiRes' module when you want to sleep. select undef, undef, undef, 0.25; # not ok use Time::HiRes; sleep( 0.25 ); # ok Builtin Functions / Prohibit Universal Can ------------------------------------------ print UNIVERSAL::can($obj, 'Foo::Bar') ? 'yes' : 'no'; #not ok print eval { $obj->can('Foo::Bar') } ? 'yes' : 'no'; #ok As of Perl 5.9.3, the use of UNIVERSAL::can as a function has been deprecated and the method form is preferred instead. Formerly, the functional form was recommended because it gave valid results even when the object was `undef' or an unblessed scalar. However, the functional form makes it impossible for packages to override `can()', a technique which is crucial for implementing mock objects and some facades. See the CPAN module the UNIVERSAL::can manpage for a more thorough discussion of this topic. Builtin Functions / Require Block Grep -------------------------------------- The expression form of `grep' and `map' is awkward and hard to read. Use the block forms instead. @matches = grep /pattern/, @list; #not ok @matches = grep { /pattern/ } @list; #ok @mapped = map transform($_), @list; #not ok @mapped = map { transform($_) } @list; #ok Builtin Functions / Prohibit Universal Isa ------------------------------------------ print UNIVERSAL::isa($obj, 'Foo::Bar') ? 'yes' : 'no'; #not ok print eval { $obj->isa('Foo::Bar') } ? 'yes' : 'no'; #ok As of Perl 5.9.3, the use of UNIVERSAL::isa as a function has been deprecated and the method form is preferred instead. Formerly, the functional form was recommended because it gave valid results even when the object was `undef' or an unblessed scalar. However, the functional form makes it impossible for packages to override `isa()', a technique which is crucial for implementing mock objects and some facades. Another alternative to UNIVERSAL::isa is the `_INSTANCE' method of Param::Util. See the CPAN module the UNIVERSAL::isa manpage for an incendiary discussion of this topic. Builtin Functions / Require Glob Function ----------------------------------------- Conway discourages the use of the `<..>' construct for globbing, as its heavily associated with I/O in most people's minds. Instead, he recommends the use of the `glob()' function as it makes it much more obvious what you're attempting to do. @files = <*.pl>; # not ok @files = glob( "*.pl" ); # ok Builtin Functions / Prohibit Lvalue Substr ------------------------------------------ Conway discourages the use of `substr()' as an lvalue, instead recommending that the 4-argument version of `substr()' be used instead. substr($something, 1, 2) = $newvalue; # not ok substr($something, 1, 2, $newvalue); # ok Builtin Functions / Prohibit Stringy Eval ----------------------------------------- The string form of eval is recompiled every time it is executed, whereas the block form is only compiled once. Also, the string form doesn't give compile-time warnings. eval "print $foo"; #not ok eval {print $foo}; #ok Builtin Functions / Require Simple Sort Block --------------------------------------------- Conway advises that sort functions should be simple. Any complicated operations on list elements should be computed and cached (perhaps via a Schwartzian Transform) before the sort rather than computed inside the sort block, because the sort block is called `N log N' times instead of just `N' times. This policy prohibits the most blatant case of complicated sort blocks: multiple statements. Future policies may wish to examine the sort block in more detail -- looking for subroutine calls or large numbers of operations. Builtin Functions / Require Block Map ------------------------------------- The expression form of `grep' and `map' is awkward and hard to read. Use the block forms instead. @matches = grep /pattern/, @list; #not ok @matches = grep { /pattern/ } @list; #ok @mapped = map transform($_), @list; #not ok @mapped = map { transform($_) } @list; #ok Class Hierarchies / Prohibit Autoloading ---------------------------------------- Declaring a subroutine with the name `"AUTOLOAD"' will violate this Policy. The `AUTOLOAD' mechanism is an easy way to generate methods for your classes, but unless they are carefully written, those classes are difficult to inherit from. And over time, the `AUTOLOAD' method will become more and more complex as it becomes responsible for dispatching more and more functions. You're better off writing explicit accessor methods. Editor macros can help make this a little easier. Class Hierarchies / Prohibit Explicit ISA ----------------------------------------- Conway recommends employing `use base qw(Foo)' instead of the usual `our @ISA = qw(Foo)' because the former happens at compile time and the latter at runtime. The `base' pragma also automatically loads `Foo' for you so you save a line of easily-forgotten code. Class Hierarchies / Prohibit One Arg Bless ------------------------------------------ Always use the two-argument form of `bless' because it allows subclasses to inherit your constructor. sub new { my $class = shift; my $self = bless {}; # not ok my $self = bless {}, $class; # ok return $self; } Regular Expressions / Require Line Boundary Matching ---------------------------------------------------- Folks coming from a `sed' or `awk' background tend to assume that `'$'' and `'^'' match the beginning and and of the line, rather than then beginning and ed of the string. Adding the '/m' flag to your regex makes it behave as most people expect it should. my $match = m{ ^ $pattern $ }x; #not ok my $match = m{ ^ $pattern $ }xm; #ok Regular Expressions / Require Extended Formatting ------------------------------------------------- Extended regular expression formatting allows you mix whitespace and comments into the pattern, thus making them much more readable. # Match a single-quoted string efficiently... m{'[^\\']*(?:\\.[^\\']*)*'}; #Huh? #Same thing with extended format... m{ ' #an opening single quote [^\\'] #any non-special chars (i.e. not backslash or single quote) (?: #then all of... \\ . # any explicitly backslashed char [^\\']* # followed by an non-special chars )* #...repeated zero or more times ' # a closing single quote }x; References / Prohibit Double Sigils ----------------------------------- When dereferencing a reference, put braces around the reference to separate the sigils. Especially for newbies, the braces eliminate any potential confusion about the relative precedence of the sigils. push @$array_ref, 'foo', 'bar', 'baz'; #not ok push @{ $array_ref }, 'foo', 'bar', 'baz'; #ok foreach ( keys %$hash_ref ){} #not ok foreach ( keys %{ $hash_ref } ){} #ok Naming Conventions / Prohibit Mixed Case Subs --------------------------------------------- Conway's recommended naming convention is to use lower-case words separated by underscores. Well-recognized acronyms can be in ALL CAPS, but must be separated by underscores from other parts of the name. sub foo_bar{} #ok sub foo_BAR{} #ok sub FOO_bar{} #ok sub FOO_BAR{} #ok sub FooBar {} #not ok sub FOObar {} #not ok sub fooBAR {} #not ok sub fooBar {} #Not ok Naming Conventions / Prohibit Mixed Case Vars --------------------------------------------- Conway's recommended naming convention is to use lower-case words separated by underscores. Well-recognized acronyms can be in ALL CAPS, but must be separated by underscores from other parts of the name. my $foo_bar #ok my $foo_BAR #ok my @FOO_bar #ok my %FOO_BAR #ok my $FooBar #not ok my $FOObar #not ok my @fooBAR #not ok my %fooBar #not ok Naming Conventions / Prohibit Ambiguous Names --------------------------------------------- Conway lists a collection of English words which are highly ambiguous as variable or subroutine names. For example, `$last' can mean previous or final. This policy tests against a list of ambiguous words for variable names. Documentation / Require Pod At End ---------------------------------- Perl stops processing code when it sees an `__END__' statement. So, to save processor cycles, it's more efficient to store all documentation after the `__END__'. Also, writing all the POD in one place usually leads to a more cohesive document, rather than being forced to follow the layout of your code. This policy issues violations if any POD is found before an `__END__'. Documentation / Require Pod Sections ------------------------------------ This Policy requires your POD to contain certain `=head1' sections. If the file doesn't contain any POD at all, then this Policy does not apply. Tools like the Module::Starter manpage make it really easy to ensure that every module has the same documentation framework, and they can save you lots of keystrokes. Code Layout / Prohibit Hard Tabs -------------------------------- Putting hard tabs in your source code (or POD) is one of the worst things you can do to your co-workers and colleagues, especially if those tabs are anywhere other than a leading position. Because various applications and devices represent tabs differently, they can cause you code to look vastly different to other people. Any decent editor can be configured to expand tabs into spaces. the Perl::Tidy manpage also does this for you. This Policy catches all tabs in your source code, including POD, quotes, and HEREDOCS. However, tabs in a leading position are allowed. If you want to forbid all tabs everywhere, put this to your .perlcriticrc file: [CodeLayout::ProhibitHardTabs] allow_leading_tabs = 0 Beware that Perl::Critic may report the location of the string that contains the tab, not the actual location of the tab, so you may need to do some hunting. I'll try and fix this in the future. Code Layout / Prohibit Quoted Word Lists ---------------------------------------- Conway doesn't mention this, but I think `qw()' is an underutilized feature of Perl. Whenever you need to declare a list of one-word literals, the `qw()' operator is wonderfully concise and saves you lots of keystrokes. And using `qw()' makes it easy to add to the list in the future. @list = ('foo', 'bar', 'baz'); #not ok @list = qw(foo bar baz); #ok Code Layout / Require Trailing Commas ------------------------------------- Conway suggests that all elements in a multi-line list should be separated by commas, including the last element. This makes it a little easier to re-order the list by cutting and pasting. my @list = ($foo, $bar, $baz); #not ok my @list = ($foo, $bar, $baz,); #ok Code Layout / Require Tidy Code ------------------------------- Conway does make specific recommendations for whitespace and curly-braces in your code, but the most important thing is to adopt a consistent layout, regardless of the specifics. And the easiest way to do that is to use the Perl::Tidy manpage. This policy will complain if you're code hasn't been run through Perl::Tidy. Code Layout / Prohibit Parens With Builtins ------------------------------------------- Conway suggests that all built-in functions should be called without parenthesis around the argument list. This reduces visual clutter and disambiguates built-in functions from user functions. Exceptions are made for `my', `local', and `our' which require parenthesis when called with multiple arguments. open($handle, '>', $filename); #not ok open $handle, '>', $filename; #ok split(/$pattern/, @list); #not ok split /$pattern/, @list; #ok Modules / Prohibit Evil Modules ------------------------------- Use this policy if you wish to prohibit the use of specific modules. These may be modules that you feel are deprecated, buggy, unsupported, insecure, or just don't like. Modules / Require Explicit Package ---------------------------------- Conway doesn't specifically mention this, but I've come across it in my own work. In general, the first statement of any Perl module or library should be a `package' statement. Otherwise, all the code that comes before the `package' statement is getting executed in the caller's package, and you have no idea who that is. Good encapsulation and common decency require your module to keep its innards to itself. As for scripts, most people understand that the default package is `main', so this Policy doesn't apply to files that begin with a perl shebang. But it you want to require an explicit `package' declaration in all files, including scripts, then add the following to your .perlcriticrc file [Modules::RequireExplicitPackage] exempt_scripts = 0 There are some valid reasons for not having a `package' statement at all. But make sure you understand them before assuming that you should do it too. Modules / Prohibit Automatic Exportation ---------------------------------------- When using the Exporter manpage, symbols placed in the `@EXPORT' variable are automatically exported into the caller's namespace. Although convenient, this practice is not polite, and may cause serious problems if the caller declares the same symbols. The best practice is to place your symbols in `@EXPORT_OK' or `%EXPORT_TAGS' and let the caller choose exactly which symbols to export. package Foo; use base qw(Exporter); our @EXPORT = qw(&foo &bar); # not ok our @EXPORT_OK = qw(&foo &bar); # ok our %EXPORT_TAGS = ( all => [ qw(&foo &bar) ] ); # ok Modules / Require End With One ------------------------------ All files included via `use' or `require' must end with a true value to indicate to the caller that the include was successful. The standard practice is to conclude your .pm files with `1;', but some authors like to get clever and return some other true value like `return "Club sandwich";'. We cannot tolerate such frivolity! OK, we can, but we don't recommend it since it confuses the newcomers. Modules / Prohibit Multiple Packages ------------------------------------ Conway doesn't specifically mention this, but I find it annoying when there are multiple packages in the same file. When searching for methods or keywords in your editor, it makes it hard to find the right chunk of code, especially if each package is a subclass of the same base. Modules / Require Version Var ----------------------------- Every Perl file (modules, libraries, and scripts) should have a `$VERSION' variable. The `$VERSION' allows clients to insist on a particular revision of your file like this: use SomeModule 2.4; #Only loads version 2.4 This Policy scans your file for any package variable named `$VERSION'. I'm assuming that you are using `strict', so you'll have to declare it like one of these: our $VERSION = 1.01; $MyPackage::VERSION = 1.01; use vars qw($VERSION); A common practice is to use the `$Revision: 431 $' keyword to automatically define the `$VERSION' variable like this: our ($VERSION) = '$Revision: 431 $' =~ m{ \$Revision: \s+ (\S+) }x; Modules / Require Bareword Includes ----------------------------------- When including another module (or library) via the `require' or `use' statements, it is best to identify the module (or library) using a bareword rather than an explicit path. This is because paths are usually not portable from one machine to another. Also, Perl automatically assumes that the filename ends in '.pm' when the library is expressed as a bareword. So as a side-effect, this Policy encourages people to write '*.pm' modules instead of the old-school '*.pl' libraries. use 'My/Perl/Module.pm'; #not ok use My::Perl::Module; #ok Miscellanea / Prohibit Formats ------------------------------ Formats are one of the oldest features of Perl. Unfortunately, they suffer from several limitations. Formats are static and cannot be easily defined at run time. Also, formats depend on several obscure global variables. For more modern reporting tools, consider using one of the template frameworks like the Template manpage or try the the Perl6::Form manpage module. Miscellanea / Prohibit Ties --------------------------- Conway discourages using `tie' to bind Perl primitive variables to user-defined objects. Unless the tie is done close to where the object is used, other developers probably won't know that the variable has special behavior. If you want to encapsulate complex behavior, just use a proper object or subroutine. Miscellanea / Require Rcs Keywords ---------------------------------- Every code file, no matter how small, should be kept in a source-control repository. Adding the magical RCS keywords to your file helps the reader know where the file comes from, in case he or she needs to modify it. This Policy scans your file for comments that look like this: # $Revision: 431 $ # $Source: /myproject/lib/foo.pm $ A common practice is to use the `Revision' keyword to automatically define the `$VERSION' variable like this: our ($VERSION) = '$Revision: 431 $' =~ m{ \$Revision: \s+ (\S+) }x; Values And Expressions / Prohibit Constant Pragma ------------------------------------------------- Named constants are a good thing. But don't use the `constant' pragma because barewords don't interpolate. Instead use the the Readonly manpage module. use constant FOOBAR => 42; #not ok use Readonly; Readonly my $FOOBAR => 42; #ok Values And Expressions / Prohibit Version Strings ------------------------------------------------- Whenever you `use' or `require' a module, you can specify a minimum version requirement. To ensure compatibility with older Perls, this version number should be expressed as a floating-point number. Do not use v-strings or three-part numbers. The Perl convention for expressing version numbers as floats is: version + (patch level / 1000). use Foo v1.2 qw(foo bar); # not ok use Foo 1.2.03 qw(foo bar); # not ok use Foo 1.00203 qw(foo bar); # ok Values And Expressions / Prohibit Escaped Characters ---------------------------------------------------- Escaped numeric values are hard to read and debug. Instead, use named values. The syntax is less compact, but dramatically more readable. $str = "\X7F\x06\x22Z"; # not ok use charnames ':full'; $str = "\N{DELETE}\N{ACKNOWLEDGE}\N{CANCEL}Z"; # ok Values And Expressions / Prohibit Leading Zeros ----------------------------------------------- Perl interprets numbers with leading zeros as octal. If that's what you really want, its better to use `oct' and make it obvious. $var = 041; #not ok, actually 33 $var = oct(41); #ok Values And Expressions / Require Number Separators -------------------------------------------------- Long numbers can be difficult to read. To improve legibility, Perl allows numbers to be split into groups of digits separated by underscores. This policy requires number sequences of more than three digits to be separated. $long_int = 123456789; #not ok $long_int = 123_456_789; #ok $long_float = 12345678.001; #not ok $long_float = 12_345_678.001; #ok Values And Expressions / Prohibit Empty Quotes ---------------------------------------------- Don't use quotes for an empty string or any string that is pure whitespace. Instead, use `q{}' to improve legibility. Better still, created named values like this. Use the `x' operator to repeat characters. $message = ''; #not ok $message = ""; #not ok $message = " "; #not ok $message = q{}; #better $message = q{ } #better $EMPTY = q{}; $message = $EMPTY; #best $SPACE = q{ }; $message = $SPACE x 5; #best Values And Expressions / Require Upper Case Heredoc Terminator -------------------------------------------------------------- For legibility, HEREDOC terminators should be all UPPER CASE letters (and numbers), without any whitespace. Conway also recommends using a standard prefix like "END_" but this policy doesn't enforce that. print <<'the End'; #not ok Hello World the End print <<'THE_END'; #ok Hello World THE_END Values And Expressions / Require Quoted Heredoc Terminator ---------------------------------------------------------- Putting single or double-quotes around your HEREDOC terminator make it obvious to the reader whether the content is going to be interpolated or not. print <, C<||>, C, or C. * Code is prefixed with a label (can potentially be reached via C) * Code is a subroutine * Control Structures / Prohibit Postfix Controls ---------------------------------------------- Conway discourages using postfix control structures (`if', `for', `unless', `until', `while'). The `unless' and `until' controls are particularly evil because they lead to double-negatives that are hard to comprehend. The only tolerable usage of a postfix `if' is when it follows a loop break such as `last', `next', `redo', or `continue'. do_something() if $condition; #not ok if($condition){ do_something() } #ok do_something() while $condition; #not ok while($condition){ do_something() } #ok do_something() unless $condition; #not ok do_something() unless ! $condition; #really bad if(! $condition){ do_something() } #ok do_something() until $condition; #not ok do_something() until ! $condition; #really bad while(! $condition){ do_something() } #ok do_something($_) for @list; #not ok LOOP: for my $n (0..100){ next if $condition; #ok last LOOP if $other_condition; #also ok } Control Structures / Prohibit Until Blocks ------------------------------------------ Conway discourages using `until' because it leads to double-negatives that are hard to understand. Instead, reverse the logic and use `while'. until($condition) { do_something() } #not ok until(! $no_flag) { do_something() } #really bad while( ! $condition) { do_something() } #ok This Policy only covers the block-form of `until'. For the postfix variety, see `ProhibitPostfixControls'. Control Structures / Prohibit CStyle For Loops ---------------------------------------------- The 3-part `for' loop that Perl inherits from C is butt-ugly, and only really necessary if you need irregular counting. The very Perlish `..' operator is much more elegant and readable. for($i=0; $i<=$max; $i++){ #ick! do_something($i); } for(0..$max){ #very nice do_something($_); } Control Structures / Prohibit Unless Blocks ------------------------------------------- Conway discourages using `unless' because it leads to double-negatives that are hard to understand. Instead, reverse the logic and use `if'. unless($condition) { do_something() } #not ok unless(! $no_flag) { do_something() } #really bad if( ! $condition) { do_something() } #ok This Policy only covers the block-form of `unless'. For the postfix variety, see `ProhibitPostfixControls'. Control Structures / Prohibit Cascading If Else ----------------------------------------------- Long `if-elsif' chains are hard to digest, especially if they are longer than a single page or screen. If testing for equality, use a hash-lookup instead. See the Switch manpage for another approach. if ($condition1) { #ok $foo = 1; } elseif ($condition2) { #ok $foo = 2; } elsif ($condition3) { #ok $foo = 3; } elsif ($condition4) { #too many! $foo = 4; } else{ #ok $foo = $default; } Variables / Prohibit Package Vars --------------------------------- Conway suggests avoiding package variables completely, because they expose your internals to other packages. Never use a package variable when a lexical variable will suffice. If your package needs to keep some dynamic state, consider using an object or closures to keep the state private. This policy assumes that you're using `strict vars' so that naked variable declarations are not package variables by default. Thus, it complains you declare a variable with `our' or `use vars', or if you make reference to variable with a fully-qualified package name. $Some::Package::foo = 1; #not ok our $foo = 1; #not ok use vars '$foo'; #not ok $foo = 1; #not allowed by 'strict' local $foo = 1; #bad taste, but technically ok. use vars '$FOO'; #ok, because it's ALL CAPS my $foo = 1; #ok In practice though, its not really practical to prohibit all package variables. Common variables like `$VERSION' and `@EXPORT' need to be global, as do any variables that you want to Export. To work around this, the Policy overlooks any variables that are in ALL_CAPS. This forces you to put all your exported variables in ALL_CAPS too, which seems to be the usual practice anyway. Variables / Prohibit Conditional Declarations --------------------------------------------- Declaring a variable with a postfix conditional is really confusing. If the conditional is false, its not clear if the variable will be false, undefined, undeclared, or what. It's much more straightforward to make variable declarations separately. my $foo = $baz if $bar; #not ok my $foo = $baz unless $bar; #not ok our $foo = $baz for @list; #not ok local $foo = $baz foreach @list; #not ok Variables / Prohibit Match Vars ------------------------------- Using the "match variables" `$`', `$&', and/or `$'' can significantly degrade the performance of a program. This policy forbids using them or their English equivalents. It also forbids plain `use English;' so you should instead employ `use English '-no_match_vars';' which avoids the match variables. See perldoc English or PBP page 82 for more information. Variables / Require Initialization For Local Vars ------------------------------------------------- Most people don't realize that a localized copy of a variable does not retain its original value. Unless you initialize the variable when you `local'-ize it, it defaults to `undef'. If you want the variable to retain its original value, just initialize it to itself. If you really do want the localized copy to be undef, then make it explicit. package Foo; $Bar = '42'; package Baz; sub frobulate { local $Foo::Bar; #not ok, local $Foo::Bar is 'undef' local $Foo::Bar = undef; #ok, local $Foo::Bar is obviously 'undef' local $Foo::Bar = $Foo::Bar; #ok, local $Foo::Bar still equals '42' } Variables / Prohibit Punctuation Vars ------------------------------------- Perl's vocabulary of punctuation variables such as `$!', `$.', and `$^' are perhaps the leading cause of its reputation as inscrutable line noise. The simple alternative is to use the the English manpage module to give them clear names. $| = undef; #not ok use English qw(-no_match_vars); local $OUTPUT_AUTOFLUSH = undef; #ok Variables / Prohibit Local Vars ------------------------------- Since Perl 5, there are very few reasons to declare `local' variables. The most common exceptions are Perl's magical global variables. If you do need to modify one of those global variables, you should localize it first. You should also use the the English manpage module to give those variables more meaningful names. local $foo; #not ok my $foo; #ok use English qw(-no_match_vars); local $INPUT_RECORD_SEPARATOR #ok local $RS #ok local $/; #not ok Variables / Protect Private Vars -------------------------------- By convention Perl authors (like authors in many other languages) indicate private methods and variables by inserting a leading underscore before the identifier. This policy catches attempts to access private variables from outside the package itself. 76