Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

Introduction to Writing Readable and Maintainable Perl (YAPC::EU 2011 Version)


Published on

An updated version of the talk I gave at FOSDEM earlier in 2011.

This one has a much better "How to approach this in the real world" section.

Published in: Technology, Art & Photos
  • I like this service ⇒ ⇐ from Academic Writers. I don't have enough time write it by myself.
    Are you sure you want to  Yes  No
    Your message goes here
  • I can advise you this service - ⇒ ⇐ Bought essay here. No problem.
    Are you sure you want to  Yes  No
    Your message goes here
  • I’ve personally never heard of companies who can produce a paper for you until word got around among my college groupmates. My professor asked me to write a research paper based on a field I have no idea about. My research skills are also very poor. So, I thought I’d give it a try. I chose a writer who matched my writing style and fulfilled every requirement I proposed. I turned my paper in and I actually got a good grade. I highly recommend ⇒ ⇐ to anyone who is in the same shoes as me.
    Are you sure you want to  Yes  No
    Your message goes here

Introduction to Writing Readable and Maintainable Perl (YAPC::EU 2011 Version)

  1. 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. 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. 3. Whats this all about?• Pragmas• CPAN• Best Perl Best Practices• The Real World• Questions
  4. 4. Pragmas
  5. 5. Always use strictuse 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. 6. ...and use warningsuse warnings ensures that odd things do not silently try to "dowhat 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. 7. Other Useful Pragmasmake open() and others die on erroruse autodie;use new Perl featuresuse feature :5.14; # enable all of themuse feature say;   # enable one at a timemake warnings throw exceptionsuse warnings FATAL => all;
  8. 8. CPAN
  9. 9. The CPANThe CPAN is by far the best thing about Perl.http://search.cpan.org98,000 modules!Using CPAN modules means your code gets maintained, bug-fixed and optimized for you!
  10. 10. Picking CPAN ModulesWith 98,000 modules it can be difficult to pick the right one...Which is the right one for the job?
  11. 11. Picking CPAN ModulesUse the CPAN Testers reports, rt bug tracker, and Reviews.Every Distribution will have these!
  12. 12. Picking CPAN ModulesThe Task::Kensho CPAN module is a documentation-and-dependencies-only distribution which can be used as arecommended modules list.Some highlights are...App::cpanminus, Test::Most, Try::Tiny,Devel::NYTProf, Perl::Critic, DateTime,Config::General, and App::Ack Its a great starting point!
  13. 13. The BestPerl Best Practices
  14. 14. Perl Best PracticesPerl Best Practices is an amazing book that was published in2005PBP contains some great tips forwriting readable and maintainablePerl code... and some silly ideaslike inside-out objects ;-)But seriously, read it. It will make youa better programmer.
  15. 15. Code in paragraphsCode 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. 16. Throw ExceptionsThere are many reasons Exceptions win out over error codes.• Impossible to ignore• Functions dont have to try to return two values• Separate exceptional from non-exceptional cases
  17. 17. Throw ExceptionsPerl implements exceptions with strings and die(). die "Exception!"; You can use eval() to catch them, but the Try::Tiny modulegives us Java-style try/catch keywords which are much nicer.try {  stuff();}catch {  # exception is in a lexically scoped $_ variable}; 
  18. 18. Use builtinsBuiltins in Perl are sensible and readable, especially when youreditor has decent syntax highlighting.Perl is excellent at string manipulation and dealing with lists.Use it to its full potential.Perls builtins have well defined names and behaviours, learn tolove them.
  19. 19. Use builtinswhile (my $line = readline $fh) {    # ...}Is more readable than...while (my $line = <$fh>) {    # ...}Especially for people less familiar with Perl!
  20. 20. Use builtinsmy @log_files = glob "*.log";Is more readable (and less prone to error) @log_files = <*.log>;(Especially when your syntax highlighter thinks that log is the log()function and highlights it yellow :-))
  21. 21. Use builtinsif (defined $value){    # stuff...}Is less prone to error than...if ($value){    # stuff...}
  22. 22. Use builtinswarn "Something went wrong!";Is way better than...print STDERR "Something went wrong!";See perldoc ­f warn for all the awesome details :-)
  23. 23. Use honorary builtinsThere are a number of "honorary builtins" which are exportedby 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. 24. Avoid overly confusing idioms and clevernessPerl 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 admittingthat some of the ways to do it suck!
  25. 25. Avoid overly confusing idioms and clevernessWhat does this do?my $result =     [ $result1 => $result2 ]  ­>[ $result2 <= $result1 ];
  26. 26. Avoid overly confusing idioms and clevernessMaybe its more obvious like this... use List::Util qw(min); my $result = min($result1, $result2);
  27. 27. The Real World
  28. 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. 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 dont agree with• Give you something to work from for code reviews
  30. 30. The Golden RulesWe have an Asimovian set of rules at the top of our CodingStyle Guide document...Rule One: Follow the style of the surrounding codeRule Two: Follow the rules of the Coding Style GuideRule Three: Follow Perl Best Practices
  31. 31. Refactoring for StyleBasically 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. 32. Perl::CriticPerl::Critic, and its executable friend perlcritic, is atool which will tell you what is wrong with your Perl code.% perlcritic
  33. 33. Perl::Critic#!/usr/bin/perluse feature say;open(IN, $0);while (<IN>) {    chomp; foreach (sort keys %letters) {    for (split //, $_) {     say "$_t$letters{$_}";        $letters{$_}++; }    }} close(IN);How many style problems can you spot?
  34. 34. Perl::Critic% perlcritic ­­verbose 11 Bareword file handle opened at line 3, near open(IN, $0);.  InputOutput::ProhibitBarewordFileHandles (Severity: 5)    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......Contains the full Perl Best Practices text!!
  35. 35. Perl::CriticHow 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!
  36. 36. Questions etc.
  37. 37. Questions?
  38. 38. Contact Me @kaokun on Twitter My Code Slides