Modern Perl
Upcoming SlideShare
Loading in...5
×
 

Modern Perl

on

  • 6,678 views

Some tools to use in actual projects

Some tools to use in actual projects

Statistics

Views

Total Views
6,678
Views on SlideShare
6,548
Embed Views
130

Actions

Likes
8
Downloads
115
Comments
1

7 Embeds 130

http://milan.pm.org 53
http://www.linkedin.com 25
http://www.semanticwave.com 22
http://www.slideshare.net 13
http://localhost 13
https://www.linkedin.com 3
http://semanticwave.com 1
More...

Accessibility

Categories

Upload Details

Uploaded via as OpenOffice

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel

11 of 1

  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
  • 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.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

    Modern Perl Modern Perl Presentation Transcript

    • Modern Perl
    • use v5.10;
    • say
      • The usual:
        • print "Hello, World! ";
        • print my_sub_call(...), " ";
      • or:
        • say 'Hello, World!';
        • say my_sub_call(...);
    • Defined or
      • The usual: $name = 'oleber' if not defined $name;
      • or $name // = 'oleber';
    • switch
        if ($value =~ /pippo/) { ... } elsif ($va1ue eq 'alpha') { ... } elsif ($value == 1 or $value == 2 ) { ... } else { ... }
    • switch
        given ($value) { when (/pippo/) { ... } when ('alpha') { ... } when ([1,2]) { ... } default { ... } }
    • Smart matching
      • The usual: if ( grep {/pippo/} @array ) { … }
      • or if ( @array ~~ /pippo/ ) { … }
    • state
      • the usual { my $static_var = 0; sub xpto { ... } }
      • or sub xpto { state $static_var = 0; ... }
    • 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
      • ...
    • Object Oriented
    • use Moose; package Person; use Moose; # now it's a Moose class! # imports strict and warnings ... no Moose ; __PACKAGE__->meta->make_immutable ;
    • 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
    • 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
        • ...
    • 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
    • Moose class Inheritance package User; use Moose; extends 'Person'; has login => ( is => 'rw', isa => 'Str', ); ... my $user = new User(id => 52, login => 'oleber')
    • 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;; }; around name => sub { my ($orig, $self, @args) = @_; return ucfirst lc $self->$orig( @args ) ; }; ...
    • 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.
    • Moose Destructor
      • If you really need it in Perl ...
      • The old DESTROY is used internally by Moose
      • You shall use the DEMOLISH() method
    • Call methods on native types
    • 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;
    • 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 { ... })
    • 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
    • Exception handling
    • 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 ;
    • TryCatch use TryCatch; try { die ... } catch ( PKG_1 $e where { $_->code > 100 } ) { ... } catch ( PKG_2 $e ) { ... } catch ( $e ) { ... } catch { ... }
    • 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
    • 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;; }
    • 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;; }
    • 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;; }
    • 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;; }
    • autodie use autodie qw(:all); open(my $FH, &quot;>>&quot;, $path); system($cmd); if ( ( my $pid = fork() ) != 0 ) { # parent } else { # child }
    • 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; } }
    • autodie vs Fatal autodie
      • Lexical scope
      • Better Errors
      Fatal
      • Package scope
      • Crazy Errors
    • Good Coding Style
    • Perl Best Practices
    • 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
    • Perltidy
      • Code Layout
        • indents.
        • reformats.
      • Very configurable Perl script that default to the perlstyle Layout
    • 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
    • Unit test
    • 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.
    • 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'); ...
    • 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
        • ...
    • ? Question & Answers