Introduction to Writing Readable and Maintainable Perl (YAPC::EU 2011 Version)
1. Introduction to writing readable
and maintainable Perl
Or
Perl Best Practices: The Best Bits
Or
Perl is more readable than Java!
Or
Your code is bad and you should feel bad
2. Who Am I?
Alex Balhatchet Working at
• Super Nerd since 1985 • 5+ years of code
• Perl Hacker since 2002 • 727 modules
• Londoner since 2004 • 1107 test files
• Paid Perl Hacker since • Lots of legacy code
2006
• All Perl
3. What's this all about?
• Pragmas
• CPAN
• Best Perl Best Practices
• The Real World
• Questions
5. Always use strict
use strict makes your code safer
• requires that all variables are declared with "my", "our", etc.
- stops you from making typos in variable names
• stops you from using symbolic (string) references
- stops you from writing terrible terrible code
• does not allow non-subroutine barewords
- stops you making typos in subroutine calls
6. ...and use warnings
use warnings ensures that odd things do not silently try to "do
what you mean."
• print undef - uninitialized value in print()
• 1 + "bananas" - non-numeric value in addition
• %hash = (1, 2, 3); - odd number of elements in hash
7. Other Useful Pragmas
make open() and others die on error
use autodie;
use new Perl features
use feature ':5.14'; # enable all of them
use feature 'say'; # enable one at a time
make warnings throw exceptions
use warnings FATAL => 'all';
9. The CPAN
The CPAN is by far the best thing about Perl.
http://search.cpan.org
98,000 modules!
Using CPAN modules means your code gets maintained, bug-
fixed and optimized for you!
10. Picking CPAN Modules
With 98,000 modules it can be difficult to pick the right one...
Which is the right one for the job?
11. Picking CPAN Modules
Use the CPAN Testers reports, rt bug tracker, and Reviews.
Every Distribution will have these!
http://search.cpan.org/dist/Data-Dumper/
12. Picking CPAN Modules
The Task::Kensho CPAN module is a documentation-and-
dependencies-only distribution which can be used as a
recommended modules list.
Some highlights are...
App::cpanminus, Test::Most, Try::Tiny,
Devel::NYTProf, Perl::Critic, DateTime,
Config::General, and App::Ack
It's a great starting point!
14. Perl Best Practices
Perl Best Practices is an amazing book that was published in
2005
PBP contains some great tips for
writing readable and maintainable
Perl code... and some silly ideas
like inside-out objects ;-)
But seriously, read it. It will make you
a better programmer.
15. Code in paragraphs
Code which is written in paragraphs is much more readable.
# get ready...
read_commandline_arguments();
init();
# actual work here...
do_stuff();
# output...
format_output();
output_stuff();
16. Throw Exceptions
There are many reasons Exceptions win out over error codes.
• Impossible to ignore
• Functions don't have to try to return two values
• Separate exceptional from non-exceptional cases
17. Throw Exceptions
Perl implements exceptions with strings and die().
die "Exception!";
You can use eval() to catch them, but the Try::Tiny module
gives us Java-style try/catch keywords which are much nicer.
try {
stuff();
}
catch {
# exception is in a lexically scoped $_ variable
};
18. Use builtins
Builtins in Perl are sensible and readable, especially when your
editor has decent syntax highlighting.
Perl is excellent at string manipulation and dealing with lists.
Use it to its full potential.
Perl's builtins have well defined names and behaviours, learn to
love them.
20. Use builtins
my @log_files = glob "*.log";
Is more readable (and less prone to error) than...
my @log_files = <*.log>;
(Especially when your syntax highlighter thinks that log is the log()
function and highlights it yellow :-))
23. Use honorary builtins
There are a number of "honorary builtins" which are exported
by core modules.
use Scalar::Util qw(looks_like_number openhandle);
use List::Util qw(first max min shuffle sum);
use List::MoreUtils qw(any all none uniq apply);
24. Avoid overly confusing idioms and cleverness
Perl lets you write code however you want.
TIMTOWTDI - There is more than one way to do it.
A big part of writing readable Perl is about admitting
that some of the ways to do it suck!
25. Avoid overly confusing idioms and cleverness
What does this do?
my $result =
[ $result1 => $result2 ]
>[ $result2 <= $result1 ];
26. Avoid overly confusing idioms and cleverness
Maybe it's more obvious like this...
use List::Util qw(min);
my $result = min($result1, $result2);
28. Why do we want maintainable code?
To be able to maintain it of course!
Especially important
• When working on a long-lived project
• When working on a team
• When team members are added frequently
29. Coding Style Guidelines
• Set out rules for all new development
• Match existing code as closely as is sensible
• Embrace the Best Practices and the Modern
• Give you something concrete to point to when somebody
writes something you don't agree with
• Give you something to work from for code reviews
30. The Golden Rules
We have an Asimovian set of rules at the top of our Coding
Style Guide document...
Rule One: Follow the style of the surrounding code
Rule Two: Follow the rules of the Coding Style Guide
Rule Three: Follow Perl Best Practices
31. Refactoring for Style
Basically follows the same rules as regular refactoring...
• Make sure there are tests
• Make sure there are good tests
• Change the whole file so that consistency is maintained
• Commit your changes to your VCS as a whole, without any
other changes!
32. Perl::Critic
Perl::Critic, and its executable friend perlcritic, is a
tool which will tell you what is wrong with your Perl code.
% perlcritic my_script.pl
35. Perl::Critic
How we use Perl::Critic at Nestoria...
●
Nightly test run critiques code
●
Writes output to a separate log file
●
If any failures occur, a single file is chosen to be the one to fix for the
day. The current “Engineer of the Week” fixes it
●
Within 3 months we had zero Perl::Critic violations!
●
New violations are solved almost immediately!
38. Contact Me
http://kaoru.slackwise.net/
@kaokun on Twitter
My Code
http://search.cpan.org/~kaoru/
https://github.com/kaoru/
Slides
http://www.slideshare.net/kaokun