Perl Elements to Avoid
Introduction
Often when people ask for help with Perl code, they show Perl code that suffers from many bad or outdated elements. This is expected, as there are many bad Perl tutorials out there, and lots of bad code that people have learned from, but it is still not desirable. In order to not get "yelled at" for using these, here is the document of the bad elements that people tend to use and some better practices that should be used instead.
A book I read said, that as opposed to most previous idea systems, they were trying to liquidate negatives instead of instilling positives in people. So in the spirit of liquidating negatives, this tutorial-in-reverse aims to show you what not to do.
Table of Contents
- Introduction
-
The List of Bad Elements
- No Indentation
- No "use strict;" and "use warnings;"
- Correct style for using the open function
- Calling variables "file"
- Identifiers without underscores
- Don't use prototypes for subroutines
- Ampersand in Subroutine Calls
- Assigning from $_
- Using "foreach" on lines
- String Notation
- Slurping a file (i.e: Reading it all into memory)
- Write code in Paragraphs using Empty Lines
- Use IO::Socket and friends instead of lower-level calls
-
Subroutine Arguments Handling
- Avoid using chop() to trim newlines characters from lines
- Don't start Modules and Packages with a Lowercase Letter
- Avoid Indirect Object Notation
- $$myarray_ref[$idx] or $$myhash_ref{$key}
- C-style for loops
- Avoid Intrusive Commenting
- Accessing Object Slots Directly
- '^' and '$' in Regular Expressions
- Magic Numbers
- String Variables Enclosed in Double Quotes
- @array[$idx] for array subscripting
- Variables called $a and $b
- Flow Control Statements Without an Explicit Label
- ($#array + 1) and Other Abuses of $#.
- $array[$#array], $array[$#array-1], etc.
- Interpolating Strings into Regular Expressions
- Overusing $_
- Mixing Tabs and Spaces
- `…` or qx// for Executing Commands
- No Explicit Returns
- "Varvarname" - Using a variable as another variable's name.
- Use Leading Underscores ('_') for Internal Methods and Functions
- print $fh @args
- Using STDIN instead of ARGV
- Modifying arrays or hashes while iterating through them.
- Comments and Identifiers in a Foreign Language
- Using perlform for formatting text.
- Using $obj->new for object construction.
- Law of Demeter
- Passing parameters in delegation
- Duplicate Code
- Long Functions and Methods
- Using map instead of foreach for side-effects
- Using grep instead of any and friends
- Using the FileHandle Module
- "Including" files instead of using Modules
- Using Global Variables as an Interface to the Module
- Declaring all variables at the top
- Using Switch.pm
- Using threads in Perl
- Sources of This Advice
The List of Bad Elements
No Indentation
Indentation means that the contents of every block are promoted from their containing environment by using a shift of some space. This makes the code easier to read and follow.
Code without indentation is harder to read and so should be avoided. The Wikipedia article lists several styles - pick one and follow it.
No "use strict;" and "use warnings;"
All modern Perl code should have the "use strict;" and "use warnings;" pragmas that prevent or warn against misspelling variable names, using undefined values, and other bad practices. So start your code (in every file) with this:
use strict; use warnings;
Or:
package MyModule; use strict; use warnings;
Correct style for using the open function
The open function is used to open files, sub-processes, etc. The correct style for it is:
open my $input_fh, "<", $input_filename
or die "Could not open '$input_filename' - $!";
the ultimately wrong, insecure and/or outdated styles are:
# Bareword filehandle (type glob), two arguments open (insecure) and no # error handling open INPUT, "<$filename"; # Also opens from $INPUT. open INPUT;
Calling variables "file"
Some people call their variables "file". However, file can mean either file handles, file names, or the contents of the file. As a result, this should be avoided and one can use the abbreviations "fh" for file handle, or "fn" for filenames instead.
Identifiers without underscores
Some people name their identifiers as several words all in lowercase and not separated by underscores ("_"). As a result, this makes the code harder to read. So instead of:
my @listofnames;
Say:
my @list_of_names;
Or maybe:
my @names_list;
Don't use prototypes for subroutines
Some people are tempted to declare their subroutines using sub my_function ($$@), with the signature of the accepted parameter types, which is called a prototype. However, this tends to break code more often than not, and should be avoided.
If you're looking for parameter lists to functions and methods, take a look at Devel-Declare from CPAN. But don't use prototypes.
For more information, see:
- Discussion on the Perl 5 Wiki
- “Why are Perl 5’s function prototypes bad?” on Stack Overflow.
Ampersand in Subroutine Calls
One should not call a subroutine using &myfunc(@args) unless you're sure that is what you want to do (like overriding prototypes). Normally saying myfunc(@args) is better.
Assigning from $_
Some people write code like the following:
while (<$my_fh>)
{
my $line = $_;
# Do something with $line…
}
Or:
foreach (@users)
{
my $user = $_;
# Process $user…
}
However, you can easily assign the explicit and lexical variables in the loop's opening line like so:
while (my $line = <$my_fh>)
{
# Do something with $line…
}
and:
foreach my $user (@users)
{
# Process $user…
}
Using "foreach" on lines
Some people may be tempted to write this code:
foreach my $line (<$my_file_handle>)
{
# Do something with $line.
}
This code appears to work but what it does is read the entire contents of the file pointed by $my_file_handle into a (potentially long) list of lines, and then iterate over them. This is inefficient. In order to read one line at a time, use this instead:
while (my $line = <$my_file_handle>)
{
# Do something with $line.
}
String Notation
Perl has a flexible way to write strings and other delimiters, and you should utilize it for clarity. If you find yourself writing long strings, write them as here-documents:
my $long_string_without_interpolation = <<'EOF'; Hello there. I am a long string. I am part of the string. And so am I. EOF
There are also <<"EOF" for strings with interpolation and <<`EOF` for trapping command output. Make sure you never use bareword here documents <<EOF which are valid syntax, but many people are never sure whether they are <<"EOF" or <<'EOF'.
If your strings are not too long but contain the special characters that correspond with the default delimiters (e.g: ', ", `, / etc.), then you can use the initial letter followed by any arbitrary delimiter notation: m{\A/home/sophie/perl}, q/My name is 'Jack' and I called my dog "Diego"./.
Slurping a file (i.e: Reading it all into memory)
One can see several bad ways to read a file into memory in Perl. Among them are:
# Not portable and suffers from possible
# shell code injection.
my $contents = `cat $filename`;
# Wasteful of CPU and memory:
my $contents = join("", <$fh>);
# Even more so:
my $contents = '';
while (my $line = <$fh>)
{
$contents .= $line;
}
You should avoid them all. Instead the proper way to read an entire file into a long string is to either use CPAN distributions for that such as File-Slurp or IO-All, or alternatively write down the following function and use it:
sub _slurp
{
my $filename = shift;
open my $in, '<', $filename
or die "Cannot open '$filename' for slurping - $!";
local $/;
my $contents = <$in>;
close($in);
return $contents;
}
Write code in Paragraphs using Empty Lines
If one of your blocks is long, split it into "code paragraphs", with empty lines between them and with each paragraph doing one thing. Then, it may be a good idea to precede each paragraph with a comment explaining what it does, or to extract it into its own function or method.
Use IO::Socket and friends instead of lower-level calls
One should use the IO::Socket family of modules for networking Input/Output instead of the lower-level socket()/connect()/bind()/etc. calls. As of this writing, perlipc contains outdated information demonstrating how to use the lower-level API which is not recommended.
Subroutine Arguments Handling
The first thing to know about handling arguments for subroutines is to avoid refering to them directly by index. Imagine you have the following code:
sub my_function
{
my $first_name = $_[0];
my $street = $_[1];
my $city = $_[2];
my $country = $_[3];
.
.
.
}
Now, what if you want to add $last_name between $first_name? You'll have to promote all the indexes afterwards! Instead do either:
sub my_function
{
my $first_name = shift;
my $street = shift;
my $city = shift;
my $country = shift;
.
.
.
}
Or:
sub my_function
{
my ($first_name, $street, $city, $country) = @_;
.
.
.
}
The same thing holds for unpacking @ARGV, the array containing the command-line arguments for a Perl program, or any other array. Don't use $ARGV[0], $ARGV[1] etc. directly, but instead unpack @ARGV using the methods given above. For processing command line arguments, you should also consider using Getopt::Long.
Don't clobber arrays or hashes
Often people ask how to pass arrays or hashes to subroutines. The answer is that the right way to do it is to pass them as a reference as an argument to the subroutine:
sub calc_polynomial
{
my ($x, $coefficients) = @_;
my $x_power = 1;
my $result = 0;
foreach my $coeff (@{$coefficients})
{
$result += $coeff * $x_power;
}
continue
{
$x_power *= $x;
}
return $result;
}
print "(4*x^2 + 2x + 1)(x = 5) = ", calc_polynomial(5, [1, 2, 4]);
You shouldn't clobber the subroutine's arguments list with entire arrays or hashes (e.g: my_func(@array1, @array2); or my_func(%myhash, $scalar) ), as this will make it difficult to extract from @_.
Named Parameters
If the number of parameters that your subroutine accepts gets too long, or if you have too many optional parameters, make sure you convert it to use named arguments. The standard way to do it is to pass a hash reference or a hash of arguments to the subroutine:
sub send_email
{
my $args = shift;
my $from_address = $args->{from};
my $to_addresses = $args->{to};
my $subject = $args->{subject};
my $body = $args->{body};
.
.
.
}
send_email(
{
from => 'shlomif@perl-begin.org',
to => ['shlomif@perl-begin.org', 'sophie@perl-begin.org'],
subject => 'Perl-Begin.org Additions',
.
.
.
}
);
Avoid using chop() to trim newlines characters from lines
Don't use the built-in function chop() in order to remove newline characters from the end of lines read using the diamond operator (<>), because this may cause the last character in a line without a line feed character to be removed. Instead, use chomp().
If you expect to process DOS/Windows-like text files whose lines end with the dual Carriage Return-Line Feed character on Unix systems then use the following in order to trim them: $line =~ s/\x0d?\x0a\z//;.
For more information see:
- "Understanding Newlines" - by Xavier Noria on OnLAMP.com.
- Wikipedia article about newlines
Don't start Modules and Packages with a Lowercase Letter
Both modules and packages (the latter also known as namespaces) and all intermediate components thereof should always start with an uppercase letter, because modules and packages that start with a lowercase letter are reserved for pragmas. So this is bad:
# Bad code: # This is file person.pm package person; use strict; use warnings; 1;
And this would be better:
# Better code! # This is file MyProject/Person.pm package MyProject::Person; use strict; use warnings; . . . 1;
Avoid Indirect Object Notation
Don't use the so-called "Indirect-object notation" which can be seen in a lot of old code and tutorials and is more prone to errors:
# Bad code: my $new_object = new MyClass @params;
Instead use the MyClass->new(…) notation:
my $new_object = MyClass->new(@params);
$$myarray_ref[$idx] or $$myhash_ref{$key}
Don't write $$myarray_ref[$idx], which is cluttered and can be easily confused with (${$myarray_ref})->[$idx]. Instead, use the arrow operator - $myarray_ref->[$idx]. This also applies for hash references - $myhash_ref->{$key}.
C-style for loops
Some beginners to Perl tend to use C-style-for-loops to loop over an array's elements:
for (my $i=0 ; $i < @array ; $i++)
{
# Do something with $array[$i]
}
However, iterating over the array itself would normally be preferable:
foreach my $elem (@array)
{
# Do something with $elem.
}
If you still need the index, do:
foreach my $idx (0 .. $#array)
{
my $elem = $array[$idx];
# Do something with $idx and $elem.
}
# perl-5.12.0 and above:
foreach my $idx (keys(@array))
{
my $elem = $array[$idx];
# Do something with $idx and $elem.
}
# Also perl-5.12.0 and above.
while (my ($idx, $elem) = each(@array))
{
# Do something with $idx and $elem.
}
An arbitrary C-style for loop can be replaced with a while loop with a continue block.
Avoid Intrusive Commenting
Some commenting is too intrusive and interrupts the flow of reading the code. Examples for that are the ######################## hard-rules that some people put in their code, the comments using multiple number signs ("#"), like ####, or excessively long comment block. Please avoid all those.
Some schools of software engineering argue that if the code's author feels that a comment is needed, it usually indicates that the code is not clear and should be factored better (like extracting a method or a subroutine with a meaningful name.). It probably does not mean that you should avoid writing comments altogether, but excessive commenting could prove as a red flag.
If you're interested in documenting the public interface of your modules and command-line programs, refer to perlpod, Perl's Plain Old Documentation (POD), which allows one to quickly and easily document one's code. POD has many extensions available on CPAN, which may prove of use.
Accessing Object Slots Directly
Since Perl objects are simple references some programmers are tempted to access them directly:
# Bad code:
$self->{'name'} = "John";
print "I am ", $self->{'age'}, " years old\n";
# Or even: (Really bad code)
$self->[NAME()] = "John";
However, this is sub-optimal as explained in the Perl for Newbies section about "Accessors", and one should use accessors using code like that:
# Good code.
$self->_name("John");
print "I am ", $self->_age(), " years old\n";
As noted in the link, you can use one of CPAN's many accessor generators to generate accessors for you.
'^' and '$' in Regular Expressions
Some people use "^" and "$" in regular expressions to mean beginning-of-the-string or end-of-the-string. However, they can mean beginning-of-a-line and end-of-a-line respectively using the /m flag which is confusing. It's a good idea to use \A for start-of-string and \z for end-of-string always, and to specify the /m flag if one needs to use "^" and "$" for start/end of a line.
Magic Numbers
Your code should not include unnamed numerical constants also known as "magic numbers" or "magic constants". For example, there is one in this code to shuffle a deck of cards:
# Bad code:
for my $i (0 .. 51)
{
my $j = $i + int(rand(52-$i));
@cards[$i,$j] = @cards[$j,$i];
}
This code is bad because the meaning of 52 and 51 is not explained and they are arbitrary. A better code would be:
# Good code.
# One of:
my $deck_size = 52;
Readonly my $deck_size => 52;
for my $i (0 .. $deck_size-1)
{
my $j = $i + int(rand($deck_size-$i));
@cards[$i,$j] = @cards[$j,$i];
}
(Of course in this case, you may opt to use a shuffle function from CPAN, but this is just for the sake of demonstration.).
String Variables Enclosed in Double Quotes
One can sometimes see people write code like that:
# Bad code:
my $name = shift(@ARGV);
print "$name", "\n";
if ("$name" =~ m{\At}i)
{
print "Your name begins with the letter 't'";
}
However, it's not necessary to enclose $name in double quotes (i.e: "$name") because it's already a string. Using it by itself as $name will do just fine:
# Better code.
my $name = shift(@ARGV);
print $name, "\n";
if ($name =~ m{\At}i)
{
print "Your name begins with the letter 't'";
}
Also see our page about text generation for other ways to delimit text.
Note that sometimes enclosing scalar variables in double-quotes makes sense - for example if they are objects with overloaded stringification. But this is the exception rather than the rule.
@array[$idx] for array subscripting
Some newcomers to Perl 5 would be tempted to write @array[$index] to subscript a single element out of the array @array. However, @array[$index] is a single-element array slice. To get a single subscript out of @array use $array[$idx] (with a dollar sign). Note that if you want to extract several elements, you can use an array slice such as @array[@indexes] or @array[$x,$y] = @array[$y,$x]. However, then it's a list which should be used in list context.
Variables called $a and $b
One should not create lexical variables called $a and $b because there are built-in-variables called that used for sorting and other uses (such as reduce in List::Util), which the lexical variables will interfere with:
# Bad code:
my ($a, $b) = @ARGV;
.
.
.
# Won't work now.
my @array = sort { length($a) <=> length($b) } @other_array;
Instead, use other single-letter variable names such as $x and $y, or better yet give more descriptive names.
Flow Control Statements Without an Explicit Label
One can sometimes see flow-control statements such as next, last or redo used without an explicit label following them, in which case they default to re-iterating or breaking out of the innermost loop. However, this is inadvisable, because later on, one may modify the code to insert a loop in between the innermost loop and the flow control statement, which will break the code. So always append a label to "next", "last" and "redo" and label your loops accordingly:
LINES:
while (my $line = <>)
{
if ($line =~ m{\A#})
{
next LINES;
}
}
($#array + 1) and Other Abuses of $#.
The $#array notation gives the last index in @array and is always equal to the array length minus one. Some people use it to signify the length of the array:
# Bad code: my @flags = ((0) x ($#names +1))
However this is unnecessary because one can better do it by evaluating @names in scalar context, possibly by saying scalar(@names).
# Better code. my @flags = ((0) x @names);
$array[$#array], $array[$#array-1], etc.
One can sometimes see people references the last elements of arrays using notation such as $array[$#array], $array[$#array-1] or even $array[scalar(@array)-1]. This duplicates the identifier and is error prone and there's a better way to do it in Perl using negative indexes. $array[-1] is the last element of the array, $array[-2] is the second-to-last, etc.
Interpolating Strings into Regular Expressions
One can often see people interpolate strings directly into regular expressions:
# Bad code:
my $username = shift(@ARGV);
open my $pass_fh, '<', '/etc/passswd'
or die "Cannot open /etc/passwd - $!";
PASSWD:
while (my $line = <$pass_fh>)
{
if ($line =~ m{\A$username}) \# Bad code here.
{
print "Your username is in /etc/passwd\n";
last PASSWD;
}
}
close($pass_fh);
The problem is that when a string is interpolated into a regular expression it is interpolated as a mini-regex, and special characters there behave like they do in a regular expression. So if I input '.*' into the command line in the program above, it will match all lines. This is a special case of code or markup injection.
The solution to this is to use \Q and \E to signify a quotemeta() portion that will treat the interpolated strings as plaintext with all the special characters escaped. So the line becomes: if ($line =~ m{\A\Q$username\E}).
Alternatively, if you do intend to interpolate a sub-regex, signify this fact with a comment. And be careful with regular expressions that are accepted from user input.
Overusing $_
It's a good idea not to overuse $_ because using it, especially in large scopes, is prone to errors, including many subtle ones. Most Perl operations support operating on other variables and you should use lexical variables with meaningful names instead of $_ whenever possible.
Some places where you have to use $_ are map, grep and other functions like that, but even in that case it might be desirable to set a lexical variable to the value of $_ right away: map { my $line = $_; … } @lines.
Mixing Tabs and Spaces
Some improperly configured text editors may be used to write code that, while indented well at a certain tab size looks terrible on other tab sizes, due to a mixture of tabs and spaces. So either use tabs for indentation or make sure your tab key expands to a constant number of spaces. You may also wish to make use of Perl-Tidy to properly format your code.
`…` or qx// for Executing Commands
Some people are tempted to use backticks (`…`) or qx/…/ for executing commands for their side-effects. E.g:
# Bad code: use strict; use warnings; my $temp_file = "tempfile.txt"; `rm -f $temp_file`;
However, this is not idiomatic because `…` and qx/…/ are used to trap a command's output and to return it as a big string or as a list of lines. It would be a better idea to use system() or to seek more idiomatic Perl-based solutions on CPAN or in the Perl core (such as using unlink() to delete a file in our case.).
Some people even go and ask how to make the qx/…/ output go to the screen, which is a clear indication that they want to use system().
No Explicit Returns
As noted in "Perl Best Practices", all functions must have an explicit return statement, as otherwise they implicitly return the last expression, which would be subject to change upon changing the code. If you don't want the subroutine to return anything (i.e: it's a so-called "procedure"), then write return; to always return a false value, which the caller won't be able to do anything meaningful with.
Another mistake is to write "return 0;" or "return undef;" to return false, because in list context, they will return a one-element list which is considered true. So always type return; to return false.
"Varvarname" - Using a variable as another variable's name.
Mark Jason Dominus has written about varvarname - "Why it's stupid to `use a variable as a variable name'", namely if $myvar is 'foobar' they want to operate on the value of $foobar. While there are ways to achieve similar things in Perl, the best way is to use hashes (possibly pointing to complex records with more information) and lookup them by the string you want to use. Read the link by MJD for more information.
Use Leading Underscores ('_') for Internal Methods and Functions
When writing a module use leading underscores in identifiers of methods and functions to signify those that are: 1. Subject to change. 2. Are used internally by the module. 3. Should not be used from outside. By using Pod-Coverage one can make sure that the external API of the module is documented and it will skip the identifiers with leading underscores, that can be thought of as "private" ones.
Here's an example:
package Math::SumOfSquares;
use strict;
use warnings;
use List::Utils qw(sum);
sub _square
{
my $n = shift;
return $n * $n;
}
sub sum_of_squares
{
my ($numbers) = @_;
return sum(map { _square($_) } @$numbers);
}
1;
print $fh @args
It is preferable to write print {$write_fh} @args over print $write_fh @args because the latter can more easily be mistaken for print $write_fh, @args (which does something different) and does not provide enough visual hints that you are writing to the $write_fh filehandle. Therefore, always wrap the file-handle in curly braces (so-called "dative block"). (Inspired by "Perl Best Practices").
Using STDIN instead of ARGV
One can write code while reading from STDIN:
# Bad code:
use strict;
use warnings;
# Strip comments.
LINES:
while (my $line = <STDIN>)
{
if ($line =~ m{\A *#})
{
next LINES;
}
print $line;
}
However, it is usually better to use ARGV instead of STDIN because it also allows processing the filenames from the command line. This can also be achieved by simply saying <>. So the code becomes:
# Better code:
use strict;
use warnings;
# Strip comments.
LINES:
while (my $line = <>)
{
if ($line =~ m{\A *#})
{
next LINES;
}
print $line;
}
Modifying arrays or hashes while iterating through them.
Some people ask about how to add or remove elements to an existing array or hash when iterating over them using foreach and other loops. The answer to that is that Perl will likely not handle it too well, and it expects that during loops the keys of a data structure will remain constant.
The best way to achieve something similar is to populate a new array or hash during the loop by using push() or a hash lookup and assignment. So do that instead.
Comments and Identifiers in a Foreign Language
Apparently, many non-native English speakers write code with comments and even identifiers in their native language. The problem with this is that programmers who do not speak that language will have a hard time understanding what is going on here, especially after the writers of the foreign language code post it in to an Internet forum in order to get help with it.
Consider what Eric Raymond wrote in his "How to Become a Hacker" document (where hacker is a software enthusiast and not a computer intruder):
4. If you don't have functional English, learn it.
As an American and native English-speaker myself, I have previously been reluctant to suggest this, lest it be taken as a sort of cultural imperialism. But several native speakers of other languages have urged me to point out that English is the working language of the hacker culture and the Internet, and that you will need to know it to function in the hacker community.
Back around 1991 I learned that many hackers who have English as a second language use it in technical discussions even when they share a birth tongue; it was reported to me at the time that English has a richer technical vocabulary than any other language and is therefore simply a better tool for the job. For similar reasons, translations of technical books written in English are often unsatisfactory (when they get done at all).
Linus Torvalds, a Finn, comments his code in English (it apparently never occurred to him to do otherwise). His fluency in English has been an important factor in his ability to recruit a worldwide community of developers for Linux. It's an example worth following.
Being a native English-speaker does not guarantee that you have language skills good enough to function as a hacker. If your writing is semi-literate, ungrammatical, and riddled with misspellings, many hackers (including myself) will tend to ignore you. While sloppy writing does not invariably mean sloppy thinking, we've generally found the correlation to be strong — and we have no use for sloppy thinkers. If you can't yet write competently, learn to.
So if you're posting code for public scrutiny, make sure it is written with English identifiers and comments.
Using perlform for formatting text.
One should not use perlform for formatting text, because it makes use of global identifiers, and should use the Perl6-Form CPAN distribution instead. Also see our text generation page for more information. (Inspired by "Perl Best Practices").
Using $obj->new for object construction.
Sometimes you can see class constructors such as:
# Bad code:
sub new
{
my $proto = shift;
my $class = ref($proto) || $proto;
my $self = {};
…
}
The problem here is that this allows one to do $my_object_instance->new to create a new instance of the object, but many people will expect it to be invalid or to clone the object. So don't do that and instead write your constructors as:
# Better code:
sub new
{
my $class = shift;
my $self = {};
bless $self, $class;
…
}
Which will disable it and will just allow ref($my_object_instance)->new(…). If you need a clone method, then code one called "clone()" and don't use "new" for that.
(Thanks to Randal L. Schwartz's post "Constructing Objects" for providing the insight to this).
Law of Demeter
See the Wikipedia article about "Law of Demeter" for more information. Namely, doing many nested method calls like $self->get_employee('sophie')->get_address()->get_street() is not advisable, and should be avoided.
A better option would be to provide methods in the containing objects to access those methods of their contained objects. And an even better way would be to structure the code so that each object handles its own domain.
Passing parameters in delegation
Sometimes we encounter a case where subroutines each pass the same parameter to one another in delegation, just because the innermost subroutines in the callstack need it.
To avoid it, create a class, and declare methods that operate on the fields of the class, where you can assign the delegated arguments.
Duplicate Code
As noted in Martin Fowler's "Refactoring" book (but held as a fact for a long time beforehand), duplicate code is a code smell, and should be avoided. The solution is to extract duplicate functionality into subroutines, methods and classes.
Long Functions and Methods
Another common code smell is long subroutines and methods. The solution to these is to extract several shorter methods out, with meaningful names.
Using map instead of foreach for side-effects
You shouldn't be using map to iterate on a list instead of foreach if you're not interested in constructing a new list and all you are interested in are the side-effects. For example:
# Bad code:
use strict;
use warnings;
map { print "Hello $_!\n"; } @ARGV;
Would be better written as:
use strict;
use warnings;
foreach my $name (@ARGV)
{
print "Hello $name!\n";
}
Which better conveys one's intention and may be a bit more efficient.
Using grep instead of any and friends
Sometimes one can see people using grep to find the first matching element in an array, or whether such an element exists at all. However, grep is intended to extract all matching elements out of a list, not just the first one, and as a result will not stop until it finds them all. To remedy this look at either first() from List::Util (to find the first match) or "any/all/notall/none" from List::MoreUtils (to find whether a single element exists). These better convey one's intention and may be more efficient because they stop on the first match.
One should note that if one does such lookups often, then they should try to use a hash instead.
Using the FileHandle Module
The FileHandle module is old and bad, and should not be used. One should use the IO::Handle family of modules instead.
"Including" files instead of using Modules
We are often asked how one can "include" a file in a Perl program (similar to PHP's include or the shell's "source" or "." operators. The answer is that the better way is to extract the common functionality from all the programs into modules and load them by using "use" or "require".
Note that do can be used to evaluate a file (but in a different scope), but it's almost always not needed.
Some people are looking to supply a common configuration to their programs as global variables in the included files, and those people should look at CPAN configration modules such as Config-IniFiles or the various JSON modules for the ability to read configuration files in a safer and better way.
Using Global Variables as an Interface to the Module
While it is possible to a large extent, one should generally not use global variables as an interface to a module, and should prefer having a procedural or an object oriented interface instead. For information about this see our page about modules and packages and our our page about object oriented programming in Perl.
Declaring all variables at the top
Some inexperienced Perl programmers, possibly by influence from languages such as C, like to declare all variables used by the program at the top of the program or the relevant subroutines. Like so:
# Bad code: my $first_name; my $last_name; my $address; my @people; my %cities; . . .
However, this is bad form in Perl, and the preferable way is to declare all the variables when they are first used, and at the innermost scope where they should retain their value. This will allow to keep track of them better.
Using Switch.pm
One should not use Switch.pm to implement a switch statement because it's a source filter, tends to break a lot of code, and causes unexpected problems. Instead one should either use given/when, which are only available in perl-5.10 and above, or dispatch tables, or alterantively plain if/elsif/else structures.
Using threads in Perl
Some beginners, when thinking they need to multitask their programs start thinking they should use perl threads. However, as mentioned in perlthrtutperlthrtut, perl threads are very much unlike the traditional thread modules, share nothing by default and are in fact heavyweight processes (instead of the usual lightweight ones). See also Elizabeth Mattijsen’s writeup about perl's ithreads on perlmonks.
To sum up, usually threads are the wrong answer and you should be using forking processes or something like POE (see our page about multitasking) instead.
Sources of This Advice
This is a short list of the sources from which this advice was taken which also contains material for further reading:
-
The Book "Perl Best Practices" by Damian Conway - contains a lot of good advice and food for thought, but sometimes should be deviated from. Also see the "PBP Module Recommendation Commentary" on the Perl 5 Wiki.
-
"Ancient Perl" on the Perl 5 Wiki.
-
Advice given by people on Freenode's #perl channel, on the Perl Beginners mailing list, and on other Perl forums.
