SlideShare uma empresa Scribd logo
1 de 36
Baixar para ler offline
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
Who Am I?

Alex Balhatchet             Working for a small company

   Super Nerd since 1985       ~5 years of code
   Perl Hacker since 2002      582 modules
   Londoner since 2004         Lots of legacy code
   Paid Perl Hacker since      All Perl
   2006
Who are you guys?

  Perl Oldies?
  Perl Newbies?
  Curious non-Perl types?
I'm here to convince you that Perl can be readable!

my @files = @ARGV;

foreach my $file (@files) {
   open(my $fh, '<', $file);

    while (my $line = readline($fh)) {
      print $line;
    }

    close($fh);
}
Summary
 Pragmas
 CPAN
 Best Perl Best Practices
 Legacy Code
 Perl::Critic & Perl::Tidy
 Questions
Pragmas
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
...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
Other Useful Pragmas

# make open() and others die on error
use autodie;

# enable say(), given(), state, etc.
use feature ':5.10'; # enable all of them
use feature 'say';                # enable one at a time

# make warnings throw exceptions
use warnings FATAL => 'all';
CPAN
The CPAN

The CPAN is by far the best thing about Perl.

http://search.cpan.org

90,000 modules!

Using CPAN modules means your code gets maintained, bug-
fixed and optimized for you!
Picking CPAN Modules

With 90,000 modules it can be difficult to pick the right one...




Which is the right one for the job?
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/

CPAN Testers: PASS (561) FAIL (8) UNKNOWN (4)

Rating:         (9 Reviews)
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!
Best Perl Best Practices
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();
Throw Exceptions

Modern programming wisdom gives us 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
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
}
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.
Use builtins

while (my $line = readline   while (my $line = <$fh>) {
($fh)) {                       # ...
   # ...                     }
}


warn "warning! something's   print STDERR "is this a warning? who
weird";                      knows?!";
Use builtins

if (defined $value){   if ($value){
    # stuff...             # stuff...
}                      }



my @files = glob("*.   my @files = <*.txt>;
txt");
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);
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!
Avoid overly confusing idioms and cleverness

What does this do?

my $result =
  [ $result1 => $result2 ]
 ->[ $result2 <= $result1 ];
Avoid overly confusing idioms and cleverness

Maybe it's more obvious like this...
 
use List::Util qw(min);
my $result = min($result1, $result2);
Legacy Code
Be consistent with existing code

This is an important rule, because it often contradicts all the
others I've mentioned:


 When dealing with an existing code base, be consistent.
Perl::Critic & Perl::Tidy
Be consistent with existing code

If you change the existing code...

   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!
Perl::Critic

Perl::Critic, and its binary friend perlcritic, is a tool which will tell
you what is wrong with your Perl code.

% perlcritic my_script.pl
Perl::Critic

#!/usr/bin/perl

use feature 'say';

open(IN, $0);
while (<IN>) {
  chomp;                 foreach (sort keys %letters) {
  for (split //, $_) {      say "$_t$letters{$_}";
     $letters{$_}++;     }
  }
}                        close(IN);




How many mistakes can you spot?
Perl::Critic

% perlcritic --verbose 11 bad_perl.pl

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!!
Perl::Tidy

Perl::Tidy, and perltidy, is a tool for automatically tidying up Perl code
to make it more readable.

It can...

    convert tabs into spaces
    restrict lines to 80 characters
    automatically line up "=>" characters in hashes and ","'s in lists
    add semi-colons where they belong
    un-cuddle elses

The perltidyrc file listed in Perl Best Practices can be found here:

http://www.perlmonks.org/?node_id=485885
Questions etc.
Questions?
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

Mais conteúdo relacionado

Mais procurados (20)

Introduction to php basics
Introduction to php   basicsIntroduction to php   basics
Introduction to php basics
 
Perl Programming - 02 Regular Expression
Perl Programming - 02 Regular ExpressionPerl Programming - 02 Regular Expression
Perl Programming - 02 Regular Expression
 
PHP7 is coming
PHP7 is comingPHP7 is coming
PHP7 is coming
 
Perl Basics with Examples
Perl Basics with ExamplesPerl Basics with Examples
Perl Basics with Examples
 
Create your own PHP extension, step by step - phpDay 2012 Verona
Create your own PHP extension, step by step - phpDay 2012 VeronaCreate your own PHP extension, step by step - phpDay 2012 Verona
Create your own PHP extension, step by step - phpDay 2012 Verona
 
Lesson 4 constant
Lesson 4  constantLesson 4  constant
Lesson 4 constant
 
How Xslate Works
How Xslate WorksHow Xslate Works
How Xslate Works
 
Unit 1-introduction to perl
Unit 1-introduction to perlUnit 1-introduction to perl
Unit 1-introduction to perl
 
Ruby cheat sheet
Ruby cheat sheetRuby cheat sheet
Ruby cheat sheet
 
php basics
php basicsphp basics
php basics
 
Ruby quick ref
Ruby quick refRuby quick ref
Ruby quick ref
 
Cross platform php
Cross platform phpCross platform php
Cross platform php
 
PHP Tips for certification - OdW13
PHP Tips for certification - OdW13PHP Tips for certification - OdW13
PHP Tips for certification - OdW13
 
Understanding PHP objects
Understanding PHP objectsUnderstanding PHP objects
Understanding PHP objects
 
Perl
PerlPerl
Perl
 
Php.ppt
Php.pptPhp.ppt
Php.ppt
 
Profiling php5 to php7
Profiling php5 to php7Profiling php5 to php7
Profiling php5 to php7
 
Free PHP Book Online | PHP Development in India
Free PHP Book Online | PHP Development in IndiaFree PHP Book Online | PHP Development in India
Free PHP Book Online | PHP Development in India
 
Quick tour of PHP from inside
Quick tour of PHP from insideQuick tour of PHP from inside
Quick tour of PHP from inside
 
Perl Moderno
Perl ModernoPerl Moderno
Perl Moderno
 

Semelhante a Introduction to writing readable and maintainable Perl

Introduction to Writing Readable and Maintainable Perl (YAPC::EU 2011 Version)
Introduction to Writing Readable and Maintainable Perl (YAPC::EU 2011 Version)Introduction to Writing Readable and Maintainable Perl (YAPC::EU 2011 Version)
Introduction to Writing Readable and Maintainable Perl (YAPC::EU 2011 Version)Alex Balhatchet
 
Introduction to perl_ a scripting language
Introduction to perl_ a scripting languageIntroduction to perl_ a scripting language
Introduction to perl_ a scripting languageVamshi Santhapuri
 
What we can learn from Rebol?
What we can learn from Rebol?What we can learn from Rebol?
What we can learn from Rebol?lichtkind
 
Bioinformatica 29-09-2011-p1-introduction
Bioinformatica 29-09-2011-p1-introductionBioinformatica 29-09-2011-p1-introduction
Bioinformatica 29-09-2011-p1-introductionProf. Wim Van Criekinge
 
Plunging Into Perl While Avoiding the Deep End (mostly)
Plunging Into Perl While Avoiding the Deep End (mostly)Plunging Into Perl While Avoiding the Deep End (mostly)
Plunging Into Perl While Avoiding the Deep End (mostly)Roy Zimmer
 
The Essential Perl Hacker's Toolkit
The Essential Perl Hacker's ToolkitThe Essential Perl Hacker's Toolkit
The Essential Perl Hacker's ToolkitStephen Scaffidi
 
Bioinformatics p1-perl-introduction v2013
Bioinformatics p1-perl-introduction v2013Bioinformatics p1-perl-introduction v2013
Bioinformatics p1-perl-introduction v2013Prof. Wim Van Criekinge
 
Low maintenance perl notes
Low maintenance perl notesLow maintenance perl notes
Low maintenance perl notesPerrin Harkins
 
Writing Readable Code
Writing Readable CodeWriting Readable Code
Writing Readable Codeeddiehaber
 
Was können wir von Rebol lernen?
Was können wir von Rebol lernen?Was können wir von Rebol lernen?
Was können wir von Rebol lernen?lichtkind
 
name name2 n
name name2 nname name2 n
name name2 ncallroom
 
name name2 n
name name2 nname name2 n
name name2 ncallroom
 

Semelhante a Introduction to writing readable and maintainable Perl (20)

Introduction to Writing Readable and Maintainable Perl (YAPC::EU 2011 Version)
Introduction to Writing Readable and Maintainable Perl (YAPC::EU 2011 Version)Introduction to Writing Readable and Maintainable Perl (YAPC::EU 2011 Version)
Introduction to Writing Readable and Maintainable Perl (YAPC::EU 2011 Version)
 
Introduction to perl_ a scripting language
Introduction to perl_ a scripting languageIntroduction to perl_ a scripting language
Introduction to perl_ a scripting language
 
What we can learn from Rebol?
What we can learn from Rebol?What we can learn from Rebol?
What we can learn from Rebol?
 
Bioinformatica 29-09-2011-p1-introduction
Bioinformatica 29-09-2011-p1-introductionBioinformatica 29-09-2011-p1-introduction
Bioinformatica 29-09-2011-p1-introduction
 
Plunging Into Perl While Avoiding the Deep End (mostly)
Plunging Into Perl While Avoiding the Deep End (mostly)Plunging Into Perl While Avoiding the Deep End (mostly)
Plunging Into Perl While Avoiding the Deep End (mostly)
 
The Essential Perl Hacker's Toolkit
The Essential Perl Hacker's ToolkitThe Essential Perl Hacker's Toolkit
The Essential Perl Hacker's Toolkit
 
PerlScripting
PerlScriptingPerlScripting
PerlScripting
 
Perl slid
Perl slidPerl slid
Perl slid
 
Bioinformatics p1-perl-introduction v2013
Bioinformatics p1-perl-introduction v2013Bioinformatics p1-perl-introduction v2013
Bioinformatics p1-perl-introduction v2013
 
Easy native wrappers with SWIG
Easy native wrappers with SWIGEasy native wrappers with SWIG
Easy native wrappers with SWIG
 
Perl Basics for Pentesters Part 1
Perl Basics for Pentesters Part 1Perl Basics for Pentesters Part 1
Perl Basics for Pentesters Part 1
 
Low maintenance perl notes
Low maintenance perl notesLow maintenance perl notes
Low maintenance perl notes
 
Perl 101
Perl 101Perl 101
Perl 101
 
Writing Readable Code
Writing Readable CodeWriting Readable Code
Writing Readable Code
 
Was können wir von Rebol lernen?
Was können wir von Rebol lernen?Was können wir von Rebol lernen?
Was können wir von Rebol lernen?
 
ppt7
ppt7ppt7
ppt7
 
ppt2
ppt2ppt2
ppt2
 
name name2 n
name name2 nname name2 n
name name2 n
 
test ppt
test ppttest ppt
test ppt
 
name name2 n
name name2 nname name2 n
name name2 n
 

Mais de Alex Balhatchet

Geocoding the World in Perl YAPC::EU 2014
Geocoding the World in Perl YAPC::EU 2014Geocoding the World in Perl YAPC::EU 2014
Geocoding the World in Perl YAPC::EU 2014Alex Balhatchet
 
Test Kit 2.0 YAPC::EU 2014 Lightning Talk
Test Kit 2.0 YAPC::EU 2014 Lightning TalkTest Kit 2.0 YAPC::EU 2014 Lightning Talk
Test Kit 2.0 YAPC::EU 2014 Lightning TalkAlex Balhatchet
 
Nestoria Dev Blog YAPC::EU 2014 Lightning Talk
Nestoria Dev Blog YAPC::EU 2014 Lightning TalkNestoria Dev Blog YAPC::EU 2014 Lightning Talk
Nestoria Dev Blog YAPC::EU 2014 Lightning TalkAlex Balhatchet
 
Test::Kit 2.0 (London.pm Technical Meeting July 2014)
Test::Kit 2.0 (London.pm Technical Meeting July 2014)Test::Kit 2.0 (London.pm Technical Meeting July 2014)
Test::Kit 2.0 (London.pm Technical Meeting July 2014)Alex Balhatchet
 
App::highlight - a simple grep-like highlighter app
App::highlight - a simple grep-like highlighter appApp::highlight - a simple grep-like highlighter app
App::highlight - a simple grep-like highlighter appAlex Balhatchet
 
Continuous testing and deployment in Perl (London.pm Technical Meeting Octobe...
Continuous testing and deployment in Perl (London.pm Technical Meeting Octobe...Continuous testing and deployment in Perl (London.pm Technical Meeting Octobe...
Continuous testing and deployment in Perl (London.pm Technical Meeting Octobe...Alex Balhatchet
 

Mais de Alex Balhatchet (8)

Geocoding the World in Perl YAPC::EU 2014
Geocoding the World in Perl YAPC::EU 2014Geocoding the World in Perl YAPC::EU 2014
Geocoding the World in Perl YAPC::EU 2014
 
Test Kit 2.0 YAPC::EU 2014 Lightning Talk
Test Kit 2.0 YAPC::EU 2014 Lightning TalkTest Kit 2.0 YAPC::EU 2014 Lightning Talk
Test Kit 2.0 YAPC::EU 2014 Lightning Talk
 
Nestoria Dev Blog YAPC::EU 2014 Lightning Talk
Nestoria Dev Blog YAPC::EU 2014 Lightning TalkNestoria Dev Blog YAPC::EU 2014 Lightning Talk
Nestoria Dev Blog YAPC::EU 2014 Lightning Talk
 
Test::Kit 2.0 (London.pm Technical Meeting July 2014)
Test::Kit 2.0 (London.pm Technical Meeting July 2014)Test::Kit 2.0 (London.pm Technical Meeting July 2014)
Test::Kit 2.0 (London.pm Technical Meeting July 2014)
 
App::highlight - a simple grep-like highlighter app
App::highlight - a simple grep-like highlighter appApp::highlight - a simple grep-like highlighter app
App::highlight - a simple grep-like highlighter app
 
Continuous testing and deployment in Perl (London.pm Technical Meeting Octobe...
Continuous testing and deployment in Perl (London.pm Technical Meeting Octobe...Continuous testing and deployment in Perl (London.pm Technical Meeting Octobe...
Continuous testing and deployment in Perl (London.pm Technical Meeting Octobe...
 
File::CleanupTask
File::CleanupTaskFile::CleanupTask
File::CleanupTask
 
Authoring CPAN modules
Authoring CPAN modulesAuthoring CPAN modules
Authoring CPAN modules
 

Introduction to writing readable and maintainable Perl

  • 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 for a small company Super Nerd since 1985 ~5 years of code Perl Hacker since 2002 582 modules Londoner since 2004 Lots of legacy code Paid Perl Hacker since All Perl 2006
  • 3. Who are you guys? Perl Oldies? Perl Newbies? Curious non-Perl types?
  • 4. I'm here to convince you that Perl can be readable! my @files = @ARGV; foreach my $file (@files) { open(my $fh, '<', $file); while (my $line = readline($fh)) { print $line; } close($fh); }
  • 5. Summary Pragmas CPAN Best Perl Best Practices Legacy Code Perl::Critic & Perl::Tidy Questions
  • 7. 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
  • 8. ...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
  • 9. Other Useful Pragmas # make open() and others die on error use autodie; # enable say(), given(), state, etc. use feature ':5.10'; # enable all of them use feature 'say'; # enable one at a time # make warnings throw exceptions use warnings FATAL => 'all';
  • 10. CPAN
  • 11. The CPAN The CPAN is by far the best thing about Perl. http://search.cpan.org 90,000 modules! Using CPAN modules means your code gets maintained, bug- fixed and optimized for you!
  • 12. Picking CPAN Modules With 90,000 modules it can be difficult to pick the right one... Which is the right one for the job?
  • 13. 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/ CPAN Testers: PASS (561) FAIL (8) UNKNOWN (4) Rating: (9 Reviews)
  • 14. 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!
  • 15. Best Perl Best Practices
  • 16. 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();
  • 17. Throw Exceptions Modern programming wisdom gives us 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
  • 18. 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 }
  • 19. 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 while (my $line = readline while (my $line = <$fh>) { ($fh)) { # ... # ... } } warn "warning! something's print STDERR "is this a warning? who weird"; knows?!";
  • 21. Use builtins if (defined $value){ if ($value){ # stuff... # stuff... } } my @files = glob("*. my @files = <*.txt>; txt");
  • 22. 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);
  • 23. 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!
  • 24. Avoid overly confusing idioms and cleverness What does this do? my $result = [ $result1 => $result2 ] ->[ $result2 <= $result1 ];
  • 25. Avoid overly confusing idioms and cleverness Maybe it's more obvious like this...   use List::Util qw(min); my $result = min($result1, $result2);
  • 27. Be consistent with existing code This is an important rule, because it often contradicts all the others I've mentioned: When dealing with an existing code base, be consistent.
  • 29. Be consistent with existing code If you change the existing code... 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!
  • 30. Perl::Critic Perl::Critic, and its binary friend perlcritic, is a tool which will tell you what is wrong with your Perl code. % perlcritic my_script.pl
  • 31. Perl::Critic #!/usr/bin/perl use feature 'say'; open(IN, $0); while (<IN>) { chomp; foreach (sort keys %letters) { for (split //, $_) { say "$_t$letters{$_}"; $letters{$_}++; } } } close(IN); How many mistakes can you spot?
  • 32. Perl::Critic % perlcritic --verbose 11 bad_perl.pl 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!!
  • 33. Perl::Tidy Perl::Tidy, and perltidy, is a tool for automatically tidying up Perl code to make it more readable. It can... convert tabs into spaces restrict lines to 80 characters automatically line up "=>" characters in hashes and ","'s in lists add semi-colons where they belong un-cuddle elses The perltidyrc file listed in Perl Best Practices can be found here: http://www.perlmonks.org/?node_id=485885
  • 36. 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