Modern Perl

Loading...

Flash Player 9 (or above) is needed to view presentations.
We have detected that you do not have it on your computer. To install it, go here.

0 comments

Post a comment

    Post a comment
    Embed Video
    Edit your comment Cancel

    3 Favorites

    Modern Perl - Presentation Transcript

    1. Modern Perl
    2. use v5.10;
    3. say
      • The usual:
        • print "Hello, World! ";
        • print my_sub_call(...), " ";
      • or:
        • say 'Hello, World!';
        • say my_sub_call(...);
    4. Defined or
      • The usual: $name = 'oleber' if not defined $name;
      • or $name // = 'oleber';
    5. switch
        if ($value =~ /pippo/) { ... } elsif ($va1ue eq 'alpha') { ... } elsif ($value == 1 or $value == 2 ) { ... } else { ... }
    6. switch
        given ($value) { when (/pippo/) { ... } when ('alpha') { ... } when ([1,2]) { ... } default { ... } }
    7. Smart matching
      • The usual: if ( grep {/pippo/} @array ) { … }
      • or if ( @array ~~ /pippo/ ) { … }
    8. state
      • the usual { my $static_var = 0; sub xpto { ... } }
      • or sub xpto { state $static_var = 0; ... }
    9. New RegExp
      • Named Capture Buffers 'Michael Jackson' =~ /( ?<fn> .*)s( ?<ln> .*)/; %+ is ('fn'=>'Michael', 'ln'=>'Jackson'}
      • &quot;K&quot; escape, floating length positive lookbehind: s/(foo)bar/$1/g becomes s/fooKbar//g
      • Backtracking control verbs
      • ...
    10. Object Oriented
    11. use Moose; package Person; use Moose; # now it's a Moose class! # imports strict and warnings ... no Moose ; __PACKAGE__->meta->make_immutable ;
    12. 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
    13. Moose Types
      • Many types are already defined like:
        • Num, Int, Str, ClassName, Ref, ScalarRef, ...
      • Even some parameterized
        • ArrayRef[Int] # an array of integers
        • HashRef[CodeRef] # a hash of str to Code ref
        • ...
    14. 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
    15. Moose class Inheritance package User; use Moose; extends 'Person'; has login => ( is => 'rw', isa => 'Str', ); ... my $user = new User(id => 52, login => 'oleber')
    16. Moose Method sub do_login { my ($self, $password) = @_; ... }
    17. 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 ) ; }; ...
    18. Moose Constructor
      • The new() method is created for you, and it simply does the right thing.
        • You should never need to define your own new() constructor!!!
      • You can provide a BUILD() method in your class. Moose will call this for you after creating a new object.
    19. Moose Destructor
      • If you really need it in Perl ...
      • The old DESTROY is used internally by Moose
      • You shall use the DEMOLISH() method
    20. Call methods on native types
    21. 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;
    22. autobox
      • It allows methods to be called on integers, floats, strings, arrays, hashes, and code references in exactly the same manner as blessed references.
        • &quot;hello world!&quot;->upper() is equivalent to SCALAR::upper(&quot;hello world!&quot;)
        • [1..10]->foreach(sub { ... }) resolves to: ARRAY::foreach([1..10], sub { ... })
    23. autobox
      • 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:
        • autobox::Core
        • Moose::Autobox
    24. Exception handling
    25. 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 ;
    26. TryCatch use TryCatch; try { die ... } catch ( PKG_1 $e where { $_->code > 100 } ) { ... } catch ( PKG_2 $e ) { ... } catch ( $e ) { ... } catch { ... }
    27. 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
    28. 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;; }
    29. 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;; }
    30. 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;; }
    31. 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;; }
    32. autodie use autodie qw(:all); open(my $FH, &quot;>>&quot;, $path); system($cmd); if ( ( my $pid = fork() ) != 0 ) { # parent } else { # child }
    33. 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; } }
    34. autodie vs Fatal autodie
      • Lexical scope
      • Better Errors
      Fatal
      • Package scope
      • Crazy Errors
    35. Good Coding Style
    36. Perl Best Practices
    37. Good Coding Style
      • Three Goals to be achieved :
        • Robustness: reduce the number of bugs.
        • Efficiency: faster code.
        • Maintainability: help you to enter &quot;in the zone&quot;.
      • Suggestions (not commandments) can be found in:
        • Damian's book Perl Best Practices
        • perldoc perlstyle
    38. Perltidy
      • Code Layout
        • indents.
        • reformats.
      • Very configurable Perl script that default to the perlstyle Layout
    39. Perlcritic
      • Perl source code analyze witch attempts to identify:
        • awkward code
        • hard to read code
        • error-prone code
        • unconventional constructs
      • Most of the rules are based on Damian Conway's book Perl Best Practices
    40. Unit test
    41. 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.
    42. 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'); ...
    43. More specific tests
      • If Test::More just isn't enough , maybe one of:
        • Test::Exception - Test exception based code
        • Test::Output - Test STDOUT and STDERR messages.
        • Test::DatabaseRow - Simple database tests
        • Test::WWW::Mechanize - Test web application
        • Apache::Test - Test Apache
        • ...
    44. ? Question & Answers
    SlideShare Zeitgeist 2009

    + Marcos RebeloMarcos Rebelo Nominate

    custom

    336 views, 3 favs, 1 embeds more stats

    Some tools to use in actual projects

    More info about this document

    © All Rights Reserved

    Go to text version

    • Total Views 336
      • 326 on SlideShare
      • 10 from embeds
    • Comments 0
    • Favorites 3
    • Downloads 6
    Most viewed embeds
    • 10 views on http://milan.pm.org

    more

    All embeds
    • 10 views on http://milan.pm.org

    less

    Flagged as inappropriate Flag as inappropriate
    Flag as inappropriate

    Select your reason for flagging this presentation as inappropriate. If needed, use the feedback form to let us know more details.

    Cancel
    File a copyright complaint
    Having problems? Go to our helpdesk?

    Categories