SlideShare une entreprise Scribd logo
1  sur  44
Modern Perl
use v5.10;
say ,[object Object]
print my_sub_call(...), "
"; ,[object Object],[object Object]
say  my_sub_call(...);
Defined or ,[object Object]
or $name  // = 'oleber';
switch ,[object Object]
switch ,[object Object]
Smart matching ,[object Object]
or if ( @array  ~~  /pippo/ ) {   … }
state ,[object Object]
or  sub xpto {   state  $static_var = 0;   ... }
New RegExp ,[object Object]
"K" 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 ,[object Object]
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 "Called login() with $pass
"; }; around  name => sub { my ($orig, $self, @args) = @_; return ucfirst lc  $self->$orig( @args ) ; }; ...
Moose Constructor ,[object Object]
Moose Destructor  ,[object Object]
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 ,[object Object]
[1..10]->foreach(sub { ... }) resolves to: ARRAY::foreach([1..10], sub { ... })
autobox ,[object Object]
Cpan has already some Packages with the most logical functions implementation. See: ,[object Object]
Moose::Autobox
Exception handling
Error use Error qw(:try); try  { throw ...; }  catch  Error::IO with { my $E = shift; warn "File $E->{'-file'} had a problem
"; }  except  { my $E = shift; warn "ERROR: " . Dumper $E; }  otherwise  { say "ALL OK
"; }  finally  { say "Finished" } ;  # 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, ">>", $path) or die "Can't open $!"; system($cmd) == 0 or die "system failed: $?"; if ( defined ( my $pid = fork() ) ) { if ( $pid != 0 ) { # parent } else { # child } } else { die "Can't fork"; }
autodie use autodie qw(:all); open(my $FH, ">>", $path) or die "Can't open $!"; system($cmd) == 0 or die "system failed: $?"; if ( defined ( my $pid = fork() ) ) { if ( $pid != 0 ) { # parent } else { # child } } else { die "Can't fork"; }

Contenu connexe

Tendances

Tendances (19)

DBIx::Class introduction - 2010
DBIx::Class introduction - 2010DBIx::Class introduction - 2010
DBIx::Class introduction - 2010
 
Puppet Camp Chicago 2014: Smoothing Troubles With Custom Types and Providers ...
Puppet Camp Chicago 2014: Smoothing Troubles With Custom Types and Providers ...Puppet Camp Chicago 2014: Smoothing Troubles With Custom Types and Providers ...
Puppet Camp Chicago 2014: Smoothing Troubles With Custom Types and Providers ...
 
Advanced Perl Techniques
Advanced Perl TechniquesAdvanced Perl Techniques
Advanced Perl Techniques
 
LPW: Beginners Perl
LPW: Beginners PerlLPW: Beginners Perl
LPW: Beginners Perl
 
Migrating to Puppet 4.0
Migrating to Puppet 4.0Migrating to Puppet 4.0
Migrating to Puppet 4.0
 
Puppet Camp Paris 2015: Power of Puppet 4 (Beginner)
Puppet Camp Paris 2015: Power of Puppet 4 (Beginner) Puppet Camp Paris 2015: Power of Puppet 4 (Beginner)
Puppet Camp Paris 2015: Power of Puppet 4 (Beginner)
 
Introduction to Perl Best Practices
Introduction to Perl Best PracticesIntroduction to Perl Best Practices
Introduction to Perl Best Practices
 
Doctrine MongoDB ODM (PDXPHP)
Doctrine MongoDB ODM (PDXPHP)Doctrine MongoDB ODM (PDXPHP)
Doctrine MongoDB ODM (PDXPHP)
 
Constructive Destructor Use
Constructive Destructor UseConstructive Destructor Use
Constructive Destructor Use
 
WordPress Cuztom Helper
WordPress Cuztom HelperWordPress Cuztom Helper
WordPress Cuztom Helper
 
Perl
PerlPerl
Perl
 
Advanced symfony Techniques
Advanced symfony TechniquesAdvanced symfony Techniques
Advanced symfony Techniques
 
Fantom and Tales
Fantom and TalesFantom and Tales
Fantom and Tales
 
Moose: Perl Objects
Moose: Perl ObjectsMoose: Perl Objects
Moose: Perl Objects
 
Perl Basics for Pentesters Part 1
Perl Basics for Pentesters Part 1Perl Basics for Pentesters Part 1
Perl Basics for Pentesters Part 1
 
Non-Relational Databases
Non-Relational DatabasesNon-Relational Databases
Non-Relational Databases
 
Replacing "exec" with a type and provider: Return manifests to a declarative ...
Replacing "exec" with a type and provider: Return manifests to a declarative ...Replacing "exec" with a type and provider: Return manifests to a declarative ...
Replacing "exec" with a type and provider: Return manifests to a declarative ...
 
ReUse Your (Puppet) Modules!
ReUse Your (Puppet) Modules!ReUse Your (Puppet) Modules!
ReUse Your (Puppet) Modules!
 
"The worst code I ever wrote"
"The worst code I ever wrote""The worst code I ever wrote"
"The worst code I ever wrote"
 

En vedette (10)

Perl5i
Perl5iPerl5i
Perl5i
 
Java. Lecture 03. OOP and UML
Java. Lecture 03. OOP and UMLJava. Lecture 03. OOP and UML
Java. Lecture 03. OOP and UML
 
Mojolicious - Perl Framework for the Real-Time Web (Lightning Talk)
Mojolicious - Perl Framework for the Real-Time Web (Lightning Talk)Mojolicious - Perl Framework for the Real-Time Web (Lightning Talk)
Mojolicious - Perl Framework for the Real-Time Web (Lightning Talk)
 
RESTful web services
RESTful web servicesRESTful web services
RESTful web services
 
A very nice presentation on Moose.
A very nice presentation on Moose.A very nice presentation on Moose.
A very nice presentation on Moose.
 
Mojolicious, real-time web framework
Mojolicious, real-time web frameworkMojolicious, real-time web framework
Mojolicious, real-time web framework
 
Modern Perl
Modern  PerlModern  Perl
Modern Perl
 
Mojolicious
MojoliciousMojolicious
Mojolicious
 
Mojolicious: what works and what doesn't
Mojolicious: what works and what doesn'tMojolicious: what works and what doesn't
Mojolicious: what works and what doesn't
 
Mojolicious and REST
Mojolicious and RESTMojolicious and REST
Mojolicious and REST
 

Similaire à Modern Perl

Good Evils In Perl (Yapc Asia)
Good Evils In Perl (Yapc Asia)Good Evils In Perl (Yapc Asia)
Good Evils In Perl (Yapc Asia)
Kang-min Liu
 
Barely Legal Xxx Perl Presentation
Barely Legal Xxx Perl PresentationBarely Legal Xxx Perl Presentation
Barely Legal Xxx Perl Presentation
Attila Balazs
 
Zendcon 2007 Features
Zendcon 2007 FeaturesZendcon 2007 Features
Zendcon 2007 Features
fivespeed5
 

Similaire à Modern Perl (20)

Good Evils In Perl (Yapc Asia)
Good Evils In Perl (Yapc Asia)Good Evils In Perl (Yapc Asia)
Good Evils In Perl (Yapc Asia)
 
Barely Legal Xxx Perl Presentation
Barely Legal Xxx Perl PresentationBarely Legal Xxx Perl Presentation
Barely Legal Xxx Perl Presentation
 
Perl Moderno
Perl ModernoPerl Moderno
Perl Moderno
 
Perl Bag of Tricks - Baltimore Perl mongers
Perl Bag of Tricks  -  Baltimore Perl mongersPerl Bag of Tricks  -  Baltimore Perl mongers
Perl Bag of Tricks - Baltimore Perl mongers
 
Zendcon 2007 Features
Zendcon 2007 FeaturesZendcon 2007 Features
Zendcon 2007 Features
 
Cleancode
CleancodeCleancode
Cleancode
 
Maybe you do not know that ...
Maybe you do not know that ...Maybe you do not know that ...
Maybe you do not know that ...
 
Perl Presentation
Perl PresentationPerl Presentation
Perl Presentation
 
Exploiting Php With Php
Exploiting Php With PhpExploiting Php With Php
Exploiting Php With Php
 
What's new in Perl 5.10?
What's new in Perl 5.10?What's new in Perl 5.10?
What's new in Perl 5.10?
 
Introduction to Perl
Introduction to PerlIntroduction to Perl
Introduction to Perl
 
Dealing with Legacy Perl Code - Peter Scott
Dealing with Legacy Perl Code - Peter ScottDealing with Legacy Perl Code - Peter Scott
Dealing with Legacy Perl Code - Peter Scott
 
Introduction to Perl - Day 1
Introduction to Perl - Day 1Introduction to Perl - Day 1
Introduction to Perl - Day 1
 
Bag of tricks
Bag of tricksBag of tricks
Bag of tricks
 
Descobrindo a linguagem Perl
Descobrindo a linguagem PerlDescobrindo a linguagem Perl
Descobrindo a linguagem Perl
 
Ods Markup And Tagsets: A Tutorial
Ods Markup And Tagsets: A TutorialOds Markup And Tagsets: A Tutorial
Ods Markup And Tagsets: A Tutorial
 
Moose (Perl 5)
Moose (Perl 5)Moose (Perl 5)
Moose (Perl 5)
 
Top 10 php classic traps confoo
Top 10 php classic traps confooTop 10 php classic traps confoo
Top 10 php classic traps confoo
 
C to perl binding
C to perl bindingC to perl binding
C to perl binding
 
Top 10 php classic traps php serbia
Top 10 php classic traps php serbiaTop 10 php classic traps php serbia
Top 10 php classic traps php serbia
 

Dernier

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
 

Dernier (20)

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
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of Brazil
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
[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
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdf
 
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?
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 

Modern Perl

  • 3.
  • 4.
  • 6.
  • 7. or $name // = 'oleber';
  • 8.
  • 9.
  • 10.
  • 11. or if ( @array ~~ /pippo/ ) { … }
  • 12.
  • 13. or sub xpto { state $static_var = 0; ... }
  • 14.
  • 15. "K" escape, floating length positive lookbehind: s/(foo)bar/$1/g becomes s/fooKbar//g
  • 17. ...
  • 19. use Moose; package Person; use Moose; # now it's a Moose class! # imports strict and warnings ... no Moose ; __PACKAGE__->meta->make_immutable ;
  • 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.
  • 22. HashRef[CodeRef] # a hash of str to Code ref
  • 23. ...
  • 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. Moose class Inheritance package User; use Moose; extends 'Person'; has login => ( is => 'rw', isa => 'Str', ); ... my $user = new User(id => 52, login => 'oleber')
  • 26. Moose Method sub do_login { my ($self, $password) = @_; ... }
  • 27. Moose method modifiers before do_login => sub { my ( $self, $pass ) = @_; warn "Called login() with $pass "; }; around name => sub { my ($orig, $self, @args) = @_; return ucfirst lc $self->$orig( @args ) ; }; ...
  • 28.
  • 29.
  • 30. The old DESTROY is used internally by Moose
  • 31. You shall use the DEMOLISH() method
  • 32. Call methods on native types
  • 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.
  • 35. [1..10]->foreach(sub { ... }) resolves to: ARRAY::foreach([1..10], sub { ... })
  • 36.
  • 37.
  • 40. Error use Error qw(:try); try { throw ...; } catch Error::IO with { my $E = shift; warn "File $E->{'-file'} had a problem "; } except { my $E = shift; warn "ERROR: " . Dumper $E; } otherwise { say "ALL OK "; } finally { say "Finished" } ; # Don't forget the trailing ;
  • 41. TryCatch use TryCatch; try { die ... } catch ( PKG_1 $e where { $_->code > 100 } ) { ... } catch ( PKG_2 $e ) { ... } catch ( $e ) { ... } catch { ... }
  • 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. autodie open(my $FH, ">>", $path) or die "Can't open $!"; system($cmd) == 0 or die "system failed: $?"; if ( defined ( my $pid = fork() ) ) { if ( $pid != 0 ) { # parent } else { # child } } else { die "Can't fork"; }
  • 44. autodie use autodie qw(:all); open(my $FH, ">>", $path) or die "Can't open $!"; system($cmd) == 0 or die "system failed: $?"; if ( defined ( my $pid = fork() ) ) { if ( $pid != 0 ) { # parent } else { # child } } else { die "Can't fork"; }
  • 45. autodie use autodie qw(:all); open(my $FH, ">>", $path); system($cmd) == 0 or die "system failed: $?"; if ( defined ( my $pid = fork() ) ) { if ( $pid != 0 ) { # parent } else { # child } } else { die "Can't fork"; }
  • 46. autodie use autodie qw(:all); open(my $FH, ">>", $path); system($cmd); if ( defined ( my $pid = fork() ) ) { if ( $pid != 0 ) { # parent } else { # child } } else { die "Can't fork"; }
  • 47. autodie use autodie qw(:all); open(my $FH, ">>", $path); system($cmd); if ( ( my $pid = fork() ) != 0 ) { # parent } else { # child }
  • 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.
  • 50.
  • 54.
  • 56.
  • 58.
  • 59.
  • 60.
  • 61. hard to read code
  • 63.
  • 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. 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.
  • 68. Test::Output - Test STDOUT and STDERR messages.
  • 69. Test::DatabaseRow - Simple database tests
  • 70. Test::WWW::Mechanize - Test web application
  • 71. Apache::Test - Test Apache
  • 72. ...
  • 73. ? Question & Answers