Modern Perl
use v5.10;
say <ul><li>The usual: </li><ul><li>print &quot;Hello, World!
&quot;;
print my_sub_call(...), &quot;
&quot;; </li></ul><li>or: </li><ul><li>say  'Hello, World!';
say  my_sub_call(...); </li></ul></ul>
Defined or <ul><li>The usual: $name = 'oleber'    if not defined $name;
or $name  // = 'oleber'; </li></ul>
switch <ul>if ($value =~ /pippo/) {   ... }  elsif ($va1ue eq 'alpha') {   ... }  elsif ($value == 1 or $value == 2 ) {   ...
switch <ul>given  ($value) {   when  (/pippo/) {   ...   }   when  ('alpha') {   ...   }   when  ([1,2]) {   ...   }   def...
Smart matching <ul><li>The usual: if ( grep {/pippo/} @array ) {   … }
or if ( @array  ~~  /pippo/ ) {   … } </li></ul>
state <ul><li>the usual {   my $static_var = 0;   sub xpto { ... } }
or  sub xpto {   state  $static_var = 0;   ... } </li></ul>
New RegExp <ul><li>Named Capture Buffers 'Michael Jackson' =~    /( ?<fn> .*)s( ?<ln> .*)/; %+ is ('fn'=>'Michael', 'ln'=>...
&quot;K&quot; escape, floating length positive lookbehind: s/(foo)bar/$1/g becomes s/fooKbar//g
Backtracking control verbs
... </li></ul>
Object Oriented
use Moose; package Person; use Moose; # now it's a Moose class! # imports  strict  and  warnings ... no Moose ; __PACKAGE_...
Moose  attributes has  id => ( is   =>  'ro' , isa  =>  'Int' , ); has  name => ( is   =>  'rw' , isa  =>  'Str' , ); my $...
Moose Types <ul><li>Many types are already defined like: </li><ul><li>Num, Int, Str, ClassName, Ref, ScalarRef, ... </li><...
HashRef[CodeRef] # a hash of str to Code ref
... </li></ul></ul>
Define your types use Moose::Util::TypeConstraints; subtype  'Telephone' =>  as   'Str' =>  where  { $_ =~ /^d+$/}; no Moo...
Moose class Inheritance package User; use Moose; extends  'Person'; has login => ( is  => 'rw', isa => 'Str', ); ... my $u...
Moose Method sub do_login { my ($self, $password) = @_; ... }
Moose method modifiers before  do_login => sub { my ( $self, $pass ) = @_; warn &quot;Called login() with $pass
&quot;; };...
Moose Constructor <ul><li>The new() method is created for you, and it simply does the right thing.  </li><ul><li>You shoul...
Moose Destructor  <ul><li>If you really need it in  Perl  ...
The old DESTROY is used  internally  by Moose
You shall use the  DEMOLISH()  method </li></ul>
Call methods on native types
autobox use JSON; say to_json [ map { $_ ** 2 } @array ]; use autobox; local *ARRAY::map = sub { my ( $self, $block ) = @_...
autobox <ul><li>It allows methods to be called on integers, floats, strings, arrays, hashes, and code references in exactl...
[1..10]->foreach(sub { ... }) resolves to: ARRAY::foreach([1..10], sub { ... }) </li></ul></ul>
autobox <ul><li>The autobox module gives the illusion that Perl's types are first-class objects.
Cpan has already some Packages with the most logical functions implementation. See: </li><ul><li>autobox::Core
Moose::Autobox  </li></ul></ul>
Exception handling
Error use Error qw(:try); try  { throw ...; }  catch  Error::IO with { my $E = shift; warn &quot;File $E->{'-file'} had a ...
TryCatch use TryCatch; try  { die ... }  catch  ( PKG_1 $e  where  { $_->code > 100 } ) { ... }  catch  ( PKG_2 $e ) { ......
It is better to die() than to return() in failure. (Paul Fenwick) The Box Jellyfish Saltwater Crocodile Blue Ring Octopus ...
autodie open(my $FH, &quot;>>&quot;, $path) or die &quot;Can't open $!&quot;; system($cmd) == 0 or die &quot;system failed...
autodie use autodie qw(:all); open(my $FH, &quot;>>&quot;, $path) or die &quot;Can't open $!&quot;; system($cmd) == 0 or d...
Upcoming SlideShare
Loading in...5
×

Modern Perl

5,102

Published on

Some tools to use in actual projects

Published in: Technology, Education
1 Comment
9 Likes
Statistics
Notes
  • Just bought the book, after upgrading to ActiveState Perl 5.12.3. Now into my second reading, I thought a presentation would a simple way to highlight my post Perl 5.10.0 education. Guess now it's time, refactor my brain.
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here
No Downloads
Views
Total Views
5,102
On Slideshare
0
From Embeds
0
Number of Embeds
2
Actions
Shares
0
Downloads
120
Comments
1
Likes
9
Embeds 0
No embeds

No notes for slide

Modern Perl

  1. 1. Modern Perl
  2. 2. use v5.10;
  3. 3. say <ul><li>The usual: </li><ul><li>print &quot;Hello, World! &quot;;
  4. 4. print my_sub_call(...), &quot; &quot;; </li></ul><li>or: </li><ul><li>say 'Hello, World!';
  5. 5. say my_sub_call(...); </li></ul></ul>
  6. 6. Defined or <ul><li>The usual: $name = 'oleber' if not defined $name;
  7. 7. or $name // = 'oleber'; </li></ul>
  8. 8. switch <ul>if ($value =~ /pippo/) { ... } elsif ($va1ue eq 'alpha') { ... } elsif ($value == 1 or $value == 2 ) { ... } else { ... } </ul>
  9. 9. switch <ul>given ($value) { when (/pippo/) { ... } when ('alpha') { ... } when ([1,2]) { ... } default { ... } } </ul>
  10. 10. Smart matching <ul><li>The usual: if ( grep {/pippo/} @array ) { … }
  11. 11. or if ( @array ~~ /pippo/ ) { … } </li></ul>
  12. 12. state <ul><li>the usual { my $static_var = 0; sub xpto { ... } }
  13. 13. or sub xpto { state $static_var = 0; ... } </li></ul>
  14. 14. New RegExp <ul><li>Named Capture Buffers 'Michael Jackson' =~ /( ?<fn> .*)s( ?<ln> .*)/; %+ is ('fn'=>'Michael', 'ln'=>'Jackson'}
  15. 15. &quot;K&quot; escape, floating length positive lookbehind: s/(foo)bar/$1/g becomes s/fooKbar//g
  16. 16. Backtracking control verbs
  17. 17. ... </li></ul>
  18. 18. Object Oriented
  19. 19. use Moose; package Person; use Moose; # now it's a Moose class! # imports strict and warnings ... no Moose ; __PACKAGE__->meta->make_immutable ;
  20. 20. Moose attributes has id => ( is => 'ro' , isa => 'Int' , ); has name => ( is => 'rw' , isa => 'Str' , ); my $person = new Person(id => 123, name => ' John '); $person->name('peter'); # OK $person->id(12); # NOK
  21. 21. Moose Types <ul><li>Many types are already defined like: </li><ul><li>Num, Int, Str, ClassName, Ref, ScalarRef, ... </li></ul><li>Even some parameterized </li><ul><li>ArrayRef[Int] # an array of integers
  22. 22. HashRef[CodeRef] # a hash of str to Code ref
  23. 23. ... </li></ul></ul>
  24. 24. Define your types use Moose::Util::TypeConstraints; subtype 'Telephone' => as 'Str' => where { $_ =~ /^d+$/}; no Moose::Util::TypeConstraints; has telephone => ( is => 'rw', isa => 'Telephone' , ); $person->telephone('35196219374'); # OK $person->telephone('XPTO'); # NOK
  25. 25. Moose class Inheritance package User; use Moose; extends 'Person'; has login => ( is => 'rw', isa => 'Str', ); ... my $user = new User(id => 52, login => 'oleber')
  26. 26. Moose Method sub do_login { my ($self, $password) = @_; ... }
  27. 27. Moose method modifiers before do_login => sub { my ( $self, $pass ) = @_; warn &quot;Called login() with $pass &quot;; }; around name => sub { my ($orig, $self, @args) = @_; return ucfirst lc $self->$orig( @args ) ; }; ...
  28. 28. Moose Constructor <ul><li>The new() method is created for you, and it simply does the right thing. </li><ul><li>You should never need to define your own new() constructor!!! </li></ul><li>You can provide a BUILD() method in your class. Moose will call this for you after creating a new object. </li></ul>
  29. 29. Moose Destructor <ul><li>If you really need it in Perl ...
  30. 30. The old DESTROY is used internally by Moose
  31. 31. You shall use the DEMOLISH() method </li></ul>
  32. 32. Call methods on native types
  33. 33. autobox use JSON; say to_json [ map { $_ ** 2 } @array ]; use autobox; local *ARRAY::map = sub { my ( $self, $block ) = @_; return [map {&$block($_)} @$self ]; }; local *ARRAY::to_json = sub { return to_json(shift); }; say @array->map( sub { $_ ** 2 } )->to_json;
  34. 34. autobox <ul><li>It allows methods to be called on integers, floats, strings, arrays, hashes, and code references in exactly the same manner as blessed references. </li><ul><li>&quot;hello world!&quot;->upper() is equivalent to SCALAR::upper(&quot;hello world!&quot;)
  35. 35. [1..10]->foreach(sub { ... }) resolves to: ARRAY::foreach([1..10], sub { ... }) </li></ul></ul>
  36. 36. autobox <ul><li>The autobox module gives the illusion that Perl's types are first-class objects.
  37. 37. Cpan has already some Packages with the most logical functions implementation. See: </li><ul><li>autobox::Core
  38. 38. Moose::Autobox </li></ul></ul>
  39. 39. Exception handling
  40. 40. Error use Error qw(:try); try { throw ...; } catch Error::IO with { my $E = shift; warn &quot;File $E->{'-file'} had a problem &quot;; } except { my $E = shift; warn &quot;ERROR: &quot; . Dumper $E; } otherwise { say &quot;ALL OK &quot;; } finally { say &quot;Finished&quot; } ; # Don't forget the trailing ;
  41. 41. TryCatch use TryCatch; try { die ... } catch ( PKG_1 $e where { $_->code > 100 } ) { ... } catch ( PKG_2 $e ) { ... } catch ( $e ) { ... } catch { ... }
  42. 42. It is better to die() than to return() in failure. (Paul Fenwick) The Box Jellyfish Saltwater Crocodile Blue Ring Octopus Stone fish Red Back Spider Funnel Web Spider
  43. 43. autodie open(my $FH, &quot;>>&quot;, $path) or die &quot;Can't open $!&quot;; system($cmd) == 0 or die &quot;system failed: $?&quot;; if ( defined ( my $pid = fork() ) ) { if ( $pid != 0 ) { # parent } else { # child } } else { die &quot;Can't fork&quot;; }
  44. 44. autodie use autodie qw(:all); open(my $FH, &quot;>>&quot;, $path) or die &quot;Can't open $!&quot;; system($cmd) == 0 or die &quot;system failed: $?&quot;; if ( defined ( my $pid = fork() ) ) { if ( $pid != 0 ) { # parent } else { # child } } else { die &quot;Can't fork&quot;; }
  45. 45. autodie use autodie qw(:all); open(my $FH, &quot;>>&quot;, $path); system($cmd) == 0 or die &quot;system failed: $?&quot;; if ( defined ( my $pid = fork() ) ) { if ( $pid != 0 ) { # parent } else { # child } } else { die &quot;Can't fork&quot;; }
  46. 46. autodie use autodie qw(:all); open(my $FH, &quot;>>&quot;, $path); system($cmd); if ( defined ( my $pid = fork() ) ) { if ( $pid != 0 ) { # parent } else { # child } } else { die &quot;Can't fork&quot;; }
  47. 47. autodie use autodie qw(:all); open(my $FH, &quot;>>&quot;, $path); system($cmd); if ( ( my $pid = fork() ) != 0 ) { # parent } else { # child }
  48. 48. autodie error analyse eval { use autodie; open(my $FH, '<', $some_file); while ( my $line = readline $FH ) { ... } close($fh); }; given ($@) { when (undef) { say &quot;No error&quot;; } when ('open') { say &quot;Error from open&quot;; } when (':io') { say &quot;Non-open, IO error.&quot;; } when (':all') { say &quot;autodie error.&quot; } default { say &quot;Not an autodie error.&quot; } }
  49. 49. autodie vs Fatal autodie <ul><li>Lexical scope
  50. 50. Better Errors </li></ul>Fatal <ul><li>Package scope
  51. 51. Crazy Errors </li></ul>
  52. 52. Good Coding Style
  53. 53. Perl Best Practices
  54. 54. Good Coding Style <ul><li>Three Goals to be achieved : </li><ul><li>Robustness: reduce the number of bugs.
  55. 55. Efficiency: faster code.
  56. 56. Maintainability: help you to enter &quot;in the zone&quot;. </li></ul><li>Suggestions (not commandments) can be found in: </li><ul><li>Damian's book Perl Best Practices
  57. 57. perldoc perlstyle </li></ul></ul>
  58. 58. Perltidy <ul><li>Code Layout </li><ul><li>indents.
  59. 59. reformats. </li></ul><li>Very configurable Perl script that default to the perlstyle Layout </li></ul>
  60. 60. Perlcritic <ul><li>Perl source code analyze witch attempts to identify: </li><ul><li>awkward code
  61. 61. hard to read code
  62. 62. error-prone code
  63. 63. unconventional constructs </li></ul><li>Most of the rules are based on Damian Conway's book Perl Best Practices </li></ul>
  64. 64. Unit test
  65. 65. Test::Simple use Test::Simple tests => 2; ok ( 1 + 1 == 2, &quot;sum&quot; ); ok ( 2 * 3 == 5, &quot;multiplication&quot;); prints: 1..2 ok 1 - sum not ok 2 - multiplication # Failed test 'multiplication' # at script.t line 6. # Looks like you failed 1 test of 2.
  66. 66. Test::More Complex stuff use Test::More 'no_plan'; ok ( 1 + 1 == 2, &quot;sum&quot; ); is ( 1 + 1, 2, 'add'); isnt ( 2 * 3, 5, 'multiplication'); is_deeply ({1..4}, {1=>2, 3=>4}, &quot;similar hash&quot;); my $str = 'Hello, World!'; like ($str, qr/Hello/, 'match'); unlike ($str, qr/Dude/, 'No way Dude'); use_ok ('Person'); can_ok ('Person', 'name'); ...
  67. 67. More specific tests <ul><li>If Test::More just isn't enough , maybe one of: </li><ul><li>Test::Exception - Test exception based code
  68. 68. Test::Output - Test STDOUT and STDERR messages.
  69. 69. Test::DatabaseRow - Simple database tests
  70. 70. Test::WWW::Mechanize - Test web application
  71. 71. Apache::Test - Test Apache
  72. 72. ... </li></ul></ul>
  73. 73. ? Question & Answers
  1. Gostou de algum slide específico?

    Recortar slides é uma maneira fácil de colecionar informações para acessar mais tarde.

×