SlideShare uma empresa Scribd logo
1 de 38
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 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
What's this all about?
• Pragmas

• CPAN

• Best Perl Best Practices

• The Real World

• 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;

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';
CPAN
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!
Picking CPAN Modules
With 98,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/
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!
The Best
Perl Best Practices
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.
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
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
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 $fh) {
    # ...
}

Is more readable than...

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


Especially for people less familiar with Perl!
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 :-))
Use builtins
if (defined $value){
    # stuff...
}

Is less prone to error than...

if ($value){
    # stuff...
}
Use builtins
warn "Something went wrong!";

Is way better than...

print STDERR "Something went wrong!";

See perldoc ­f warn for all the awesome details :-)
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);
The Real World
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
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
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
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!
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
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 style problems 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::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!
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

ShaREing Is Caring
ShaREing Is CaringShaREing Is Caring
ShaREing Is Caring
sporst
 
Ruby 程式語言綜覽簡介
Ruby 程式語言綜覽簡介Ruby 程式語言綜覽簡介
Ruby 程式語言綜覽簡介
Wen-Tien Chang
 
Listen and look at your PHP code
Listen and look at your PHP codeListen and look at your PHP code
Listen and look at your PHP code
Gabriele Santini
 
Speed geeking-lotusscript
Speed geeking-lotusscriptSpeed geeking-lotusscript
Speed geeking-lotusscript
Bill Buchan
 
20111018 boost and gtest
20111018 boost and gtest20111018 boost and gtest
20111018 boost and gtest
Will Shen
 

Mais procurados (20)

ShaREing Is Caring
ShaREing Is CaringShaREing Is Caring
ShaREing Is Caring
 
Ruby 程式語言綜覽簡介
Ruby 程式語言綜覽簡介Ruby 程式語言綜覽簡介
Ruby 程式語言綜覽簡介
 
Better rspec 進擊的 RSpec
Better rspec 進擊的 RSpecBetter rspec 進擊的 RSpec
Better rspec 進擊的 RSpec
 
Coder sans peur du changement avec la meme pas mal hexagonal architecture
Coder sans peur du changement avec la meme pas mal hexagonal architectureCoder sans peur du changement avec la meme pas mal hexagonal architecture
Coder sans peur du changement avec la meme pas mal hexagonal architecture
 
Listen and look at your PHP code
Listen and look at your PHP codeListen and look at your PHP code
Listen and look at your PHP code
 
Listen afup 2010
Listen afup 2010Listen afup 2010
Listen afup 2010
 
groovy & grails - lecture 1
groovy & grails - lecture 1groovy & grails - lecture 1
groovy & grails - lecture 1
 
How to Reverse Engineer Web Applications
How to Reverse Engineer Web ApplicationsHow to Reverse Engineer Web Applications
How to Reverse Engineer Web Applications
 
Speed geeking-lotusscript
Speed geeking-lotusscriptSpeed geeking-lotusscript
Speed geeking-lotusscript
 
Ruby for Java Developers
Ruby for Java DevelopersRuby for Java Developers
Ruby for Java Developers
 
php 7.4 for word press developers
php 7.4 for word press developersphp 7.4 for word press developers
php 7.4 for word press developers
 
PhpSpec: practical introduction
PhpSpec: practical introductionPhpSpec: practical introduction
PhpSpec: practical introduction
 
TypeProf for IDE: Enrich Development Experience without Annotations
TypeProf for IDE: Enrich Development Experience without AnnotationsTypeProf for IDE: Enrich Development Experience without Annotations
TypeProf for IDE: Enrich Development Experience without Annotations
 
Php Tutorial
Php TutorialPhp Tutorial
Php Tutorial
 
C++ boot camp part 1/2
C++ boot camp part 1/2C++ boot camp part 1/2
C++ boot camp part 1/2
 
PHP7: Hello World!
PHP7: Hello World!PHP7: Hello World!
PHP7: Hello World!
 
Introduction to Python for Security Professionals
Introduction to Python for Security ProfessionalsIntroduction to Python for Security Professionals
Introduction to Python for Security Professionals
 
Java SE 8 best practices
Java SE 8 best practicesJava SE 8 best practices
Java SE 8 best practices
 
20111018 boost and gtest
20111018 boost and gtest20111018 boost and gtest
20111018 boost and gtest
 
Object Oriented Design Patterns for PHP
Object Oriented Design Patterns for PHPObject Oriented Design Patterns for PHP
Object Oriented Design Patterns for PHP
 

Destaque

Destaque (9)

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
 
Alsis Cierra Alsis Mexico Opportunities Fund
Alsis Cierra Alsis Mexico Opportunities FundAlsis Cierra Alsis Mexico Opportunities Fund
Alsis Cierra Alsis Mexico Opportunities Fund
 
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
 
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)
 
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
 
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
 
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...
 
[D14] MySQL 5.6時代のパフォーマンスチューニング *db tech showcase 2013 Tokyo
[D14] MySQL 5.6時代のパフォーマンスチューニング *db tech showcase 2013 Tokyo[D14] MySQL 5.6時代のパフォーマンスチューニング *db tech showcase 2013 Tokyo
[D14] MySQL 5.6時代のパフォーマンスチューニング *db tech showcase 2013 Tokyo
 
AppSec And Microservices
AppSec And MicroservicesAppSec And Microservices
AppSec And Microservices
 

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

20140406 loa days-tdd-with_puppet_tutorial
20140406 loa days-tdd-with_puppet_tutorial20140406 loa days-tdd-with_puppet_tutorial
20140406 loa days-tdd-with_puppet_tutorial
garrett honeycutt
 
これからのPerlプロダクトのかたち(YAPC::Asia 2013)
これからのPerlプロダクトのかたち(YAPC::Asia 2013)これからのPerlプロダクトのかたち(YAPC::Asia 2013)
これからのPerlプロダクトのかたち(YAPC::Asia 2013)
goccy
 

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

Introduction to writing readable and maintainable Perl
Introduction to writing readable and maintainable PerlIntroduction to writing readable and maintainable Perl
Introduction to writing readable and maintainable Perl
 
20140406 loa days-tdd-with_puppet_tutorial
20140406 loa days-tdd-with_puppet_tutorial20140406 loa days-tdd-with_puppet_tutorial
20140406 loa days-tdd-with_puppet_tutorial
 
Low maintenance perl notes
Low maintenance perl notesLow maintenance perl notes
Low maintenance perl notes
 
Bioinformatics p1-perl-introduction v2013
Bioinformatics p1-perl-introduction v2013Bioinformatics p1-perl-introduction v2013
Bioinformatics p1-perl-introduction v2013
 
Writing Readable Code
Writing Readable CodeWriting Readable Code
Writing Readable Code
 
The problem with Perl
The problem with PerlThe problem with Perl
The problem with Perl
 
Perl 101
Perl 101Perl 101
Perl 101
 
Introduction to Perl
Introduction to PerlIntroduction to Perl
Introduction to Perl
 
Better detection of what modules are used by some Perl 5 code
Better detection of what modules are used by some Perl 5 codeBetter detection of what modules are used by some Perl 5 code
Better detection of what modules are used by some Perl 5 code
 
What we can learn from Rebol?
What we can learn from Rebol?What we can learn from Rebol?
What we can learn from Rebol?
 
The Essential Perl Hacker's Toolkit
The Essential Perl Hacker's ToolkitThe Essential Perl Hacker's Toolkit
The Essential Perl Hacker's Toolkit
 
これからのPerlプロダクトのかたち(YAPC::Asia 2013)
これからのPerlプロダクトのかたち(YAPC::Asia 2013)これからのPerlプロダクトのかたち(YAPC::Asia 2013)
これからのPerlプロダクトのかたち(YAPC::Asia 2013)
 
Pugs: A Perl 6 Implementation
Pugs: A Perl 6 ImplementationPugs: A Perl 6 Implementation
Pugs: A Perl 6 Implementation
 
Adventures in Asymmetric Warfare
Adventures in Asymmetric WarfareAdventures in Asymmetric Warfare
Adventures in Asymmetric Warfare
 
Packaging perl (LPW2010)
Packaging perl (LPW2010)Packaging perl (LPW2010)
Packaging perl (LPW2010)
 
Functional Programming for Busy Object Oriented Programmers
Functional Programming for Busy Object Oriented ProgrammersFunctional Programming for Busy Object Oriented Programmers
Functional Programming for Busy Object Oriented Programmers
 
Weird Plsql
Weird PlsqlWeird Plsql
Weird Plsql
 
Getting testy with Perl
Getting testy with PerlGetting testy with Perl
Getting testy with Perl
 
Intro to Perl
Intro to PerlIntro to Perl
Intro to Perl
 
Ruby Hell Yeah
Ruby Hell YeahRuby Hell Yeah
Ruby Hell Yeah
 

Último

Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
vu2urc
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
Enterprise Knowledge
 

Último (20)

04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 

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