SlideShare a Scribd company logo
Moose




Sawyer X
Sawyer X
blogs.perl.org/users/sawyer_x
search.cpan.org/~xsawyerx
metacpan.org/author/XSAWYERX
github.com/xsawyerx/
„The Dancer guy!“
Projects: Dancer, Module::Starter, MetaCPAN::API,
 MooseX::Role::Loggable, etc.
Moose
Object system
Metaclass-based
Advanced
Sophisticated
Extensible
Production-ready
… but why Moose?
package Person;                                            package User;

use strict;                                                use Email::Valid;
use warnings;                                              use Moose;
                                                           use Moose::Util::TypeConstraints;
use Carp qw( confess );
use DateTime;                                              extends 'Person';
use DateTime::Format::Natural;
                                                           subtype 'Email'
                                                               => as 'Str'
sub new {                                                      => where { Email::Valid­>address($_) }
    my $class = shift;                                         => message { "$_ is not a valid email 
    my %p = ref $_[0] ? %{ $_[0] } : @_;                   address" };

    exists $p{name}                                        has email_address => (
        or confess 'name is a required attribute';             is       => 'rw',
    $class­>_validate_name( $p{name} );                        isa      => 'Email',
                                                               required => 1,
    exists $p{birth_date}                                  );
        or confess 'birth_date is a required attribute';

    $p{birth_date} = $class­
>_coerce_birth_date( $p{birth_date} );
    $class­>_validate_birth_date( $p{birth_date} );

    $p{shirt_size} = 'l'
        unless exists $p{shirt_size}:

    $class­>_validate_shirt_size( $p{shirt_size} );

    return bless %p, $class;
}

sub _validate_name {
    shift;
    my $name = shift;

    local $Carp::CarpLevel = $Carp::CarpLevel + 1;

    defined $name
        or confess 'name must be a string';
}
Get it?
Writing objects in basic Perl 5
Create a reference (usually to a hash)
Connect it to a package (using „bless“)
Provide subroutines that access the hash keys
Error check the hell out of it
Writing objects in basic Perl 5, e.g.
package Dog;
use strict; use warnings;
sub new {
     my $class = shift;
     my $self   = bless {}, $class;
     return $self;
}
1;
Issues
Defining the same new() concept every time
No parameters for new() yet
Will have to do all error-checking manually
Moose
package Dog;


use Moose;


1;
You get
use strict;
use warnings;
new() method
To hell with ponies, you get a moose!
(roll picture of a moose beating a pony in soccer)
Full affordance accessors (attributes)
has name => ( is => 'rw' );
„ro“ is available for read-only attributes
You can manually change setter/getter via writer/reader
Attributes can have defaults
Attributes can have type constraints
Attributes can have traits
Attributes can be lazy, have builders, clearers, predicates...
Type constraints
has name => ( is => 'ro', isa => 'Str' );
Str, Int, Bool, ArrayRef, HashRef, CodeRef, Regex,
 Classes
Combine: ArrayRef|HashRef, ArrayRef[Str]
Derivatives (Int is a Num)
Create your own using subtype, available at
 Moose::Util::TypeConstraints
Methods
Same as before
sub run {
      my $self = shift;
       say qq{I make it a habit only to run when
    being chased!};
}
Inheritance easy as...
package Punk
use Moose;
extends 'Person';
Multiple inheritance also possible (extends accepts array)
package Child;
use Moose;
extends qw/Father Mother/;
Roles are even better
package Punk;
use Moose;
with qw/Tattoos Piercings Squatter/;


Roles are things you do, instead of things you are.
More hooks than a coat rack!
package User::WinterAware;
use Moose;
extends 'User';
before leaving => sub {
  my $self = shift;
  $self->cold and $self->take_jacket;
};
More hooks than a coat rack!
package User::Secure;
use Moose;
extends 'User';
around login => sub {
  my $orig = shift;
  my $self = shift;
  $self->security_check and $self->$orig(@_);
};
More hooks than a coat rack!
Before
After
Around
Inner
Augment
Back to attributes...
has set => (
  is         => 'rw',
  isa        => 'Set::Object',
  default    => sub { Set::Object->new },
  required   => 1,
  lazy       => 1,
  predicate => 'has_set',
  clearer    => 'clear_set',
Attribute options: default
default => 'kitteh'                  # string
default => 3                         # number
default => sub { {} }                # HashRef
default => sub { [] }                # ArrayRef
default => sub { Object->new } # an Object


    (if you need a more elaborate sub, use builder)
Attribute options: required
required => 1 # required
required => 0 # not required
Attribute options: lazy
lazy => 1 # make it lazy


Class will not create the slot for this attribute unless it
absolutely has to, defined by whether it is accessed at all.


No access? No penalty!
Lazy == good
Attribute options: builder
builder => 'build_it' # subroutine name


sub build_it {
    my $self = shift; # not a problem!
  return Some::Object->new( $self-
>more_opts );
}
Attribute options: clearer
clearer => 'clear_it' # subroutine name


# you don't need to create the subroutine
sub time_machine {
    my $self = shift;
    $self->clear_it; # 'it' never happened :)
}
Attribute options: predicate
predicate => 'has_it' # subroutine name


# you don't need to create the subroutine
sub try_to_do_it {
    my $self = shift;
    $self->has_it && $self->do_it();
}
Attribute options: lazy_build
lazy_build => 1 # <3


# the same as:
lazy        => 1,
builder     => '_build_it', # private
clearer     => 'clear_it',
predicate => 'has_it',
Example: Comican
A hub for various comics strips
Allow you to fetch comic strips
Standard uniformed interface to add more comics
We'll be using:
  Roles
  Lazy attributes
  Overriding attributes options
  Attribute predicates
Comican
      comic modules        Comican::Comic::Dilber
                                     t              interface
                                                      role
       Comican::Comic::PennyArcade

Comican::Comic::xkcd                                 Comican::
                                                    Role::Comic

                          main module
   user


                             Comican.pm
Comican: overall
Comican.pm is the user's interface
It's a hub for Comican::Comic::* modules
They are objects that fetch specific comic strips
They have a common interface
Defined by Comican::Role::Comic
SHOW ME THE CODE!
/^M(?:o(?:o|[ou]se)?)?$/
Moose: standart
Mouse: subset, uses XS, faster
(Any::Moose: use Mouse unless Moose already loaded)
Moo: Pure-Perl, subset, blazing fast
Mo: As little as possible (incl. character count)
M: Really as little as possible
Hummus (HuMoose): Incompatible chickpeas paste
Thank you.

More Related Content

What's hot

Introduction To Moose
Introduction To MooseIntroduction To Moose
Introduction To Moose
Mike Whitaker
 
CoffeeScript
CoffeeScriptCoffeeScript
CoffeeScriptNone
 
Introduction to CoffeeScript
Introduction to CoffeeScriptIntroduction to CoffeeScript
Introduction to CoffeeScript
Stalin Thangaraj
 
DBIx::Class beginners
DBIx::Class beginnersDBIx::Class beginners
DBIx::Class beginners
leo lapworth
 
DBIx::Class introduction - 2010
DBIx::Class introduction - 2010DBIx::Class introduction - 2010
DBIx::Class introduction - 2010
leo lapworth
 
Writing Friendly libraries for CodeIgniter
Writing Friendly libraries for CodeIgniterWriting Friendly libraries for CodeIgniter
Writing Friendly libraries for CodeIgniterCodeIgniter Conference
 
Doctrine MongoDB ODM (PDXPHP)
Doctrine MongoDB ODM (PDXPHP)Doctrine MongoDB ODM (PDXPHP)
Doctrine MongoDB ODM (PDXPHP)
Kris Wallsmith
 
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)
Puppet
 
Power of Puppet 4
Power of Puppet 4Power of Puppet 4
Power of Puppet 4
Martin Alfke
 
Good Evils In Perl
Good Evils In PerlGood Evils In Perl
Good Evils In PerlKang-min Liu
 
LPW: Beginners Perl
LPW: Beginners PerlLPW: Beginners Perl
LPW: Beginners Perl
Dave Cross
 
WordPress Cuztom Helper
WordPress Cuztom HelperWordPress Cuztom Helper
WordPress Cuztom Helper
slicejack
 
"The worst code I ever wrote"
"The worst code I ever wrote""The worst code I ever wrote"
"The worst code I ever wrote"
Tomas Doran
 
Constructive Destructor Use
Constructive Destructor UseConstructive Destructor Use
Constructive Destructor Use
metaperl
 
Perl
PerlPerl
Going crazy with Node.JS and CakePHP
Going crazy with Node.JS and CakePHPGoing crazy with Node.JS and CakePHP
Going crazy with Node.JS and CakePHP
Mariano Iglesias
 
Advanced Perl Techniques
Advanced Perl TechniquesAdvanced Perl Techniques
Advanced Perl Techniques
Dave Cross
 
Introduction to Perl Best Practices
Introduction to Perl Best PracticesIntroduction to Perl Best Practices
Introduction to Perl Best Practices
José Castro
 
Your JavaScript Library
Your JavaScript LibraryYour JavaScript Library
Your JavaScript Library
Dmitry Baranovskiy
 

What's hot (20)

Introduction To Moose
Introduction To MooseIntroduction To Moose
Introduction To Moose
 
CoffeeScript
CoffeeScriptCoffeeScript
CoffeeScript
 
Introduction to CoffeeScript
Introduction to CoffeeScriptIntroduction to CoffeeScript
Introduction to CoffeeScript
 
Coffee Script
Coffee ScriptCoffee Script
Coffee Script
 
DBIx::Class beginners
DBIx::Class beginnersDBIx::Class beginners
DBIx::Class beginners
 
DBIx::Class introduction - 2010
DBIx::Class introduction - 2010DBIx::Class introduction - 2010
DBIx::Class introduction - 2010
 
Writing Friendly libraries for CodeIgniter
Writing Friendly libraries for CodeIgniterWriting Friendly libraries for CodeIgniter
Writing Friendly libraries for CodeIgniter
 
Doctrine MongoDB ODM (PDXPHP)
Doctrine MongoDB ODM (PDXPHP)Doctrine MongoDB ODM (PDXPHP)
Doctrine MongoDB ODM (PDXPHP)
 
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)
 
Power of Puppet 4
Power of Puppet 4Power of Puppet 4
Power of Puppet 4
 
Good Evils In Perl
Good Evils In PerlGood Evils In Perl
Good Evils In Perl
 
LPW: Beginners Perl
LPW: Beginners PerlLPW: Beginners Perl
LPW: Beginners Perl
 
WordPress Cuztom Helper
WordPress Cuztom HelperWordPress Cuztom Helper
WordPress Cuztom Helper
 
"The worst code I ever wrote"
"The worst code I ever wrote""The worst code I ever wrote"
"The worst code I ever wrote"
 
Constructive Destructor Use
Constructive Destructor UseConstructive Destructor Use
Constructive Destructor Use
 
Perl
PerlPerl
Perl
 
Going crazy with Node.JS and CakePHP
Going crazy with Node.JS and CakePHPGoing crazy with Node.JS and CakePHP
Going crazy with Node.JS and CakePHP
 
Advanced Perl Techniques
Advanced Perl TechniquesAdvanced Perl Techniques
Advanced Perl Techniques
 
Introduction to Perl Best Practices
Introduction to Perl Best PracticesIntroduction to Perl Best Practices
Introduction to Perl Best Practices
 
Your JavaScript Library
Your JavaScript LibraryYour JavaScript Library
Your JavaScript Library
 

Viewers also liked

Java. Lecture 03. OOP and UML
Java. Lecture 03. OOP and UMLJava. Lecture 03. OOP and UML
Java. Lecture 03. OOP and UMLcolriot
 
A very nice presentation on Moose.
A very nice presentation on Moose.A very nice presentation on Moose.
A very nice presentation on Moose.
Chankey Pathak
 
Moose workshop
Moose workshopMoose workshop
Moose workshop
Ynon Perek
 
Firewall in Perl by Chankey Pathak
Firewall in Perl by Chankey PathakFirewall in Perl by Chankey Pathak
Firewall in Perl by Chankey Pathak
Chankey Pathak
 
Moose Hacking Guide
Moose Hacking GuideMoose Hacking Guide
Moose Hacking Guide
guest6b8f09
 
Introduction to Perl MAGIC
Introduction to Perl MAGICIntroduction to Perl MAGIC
Introduction to Perl MAGIC
guest6b8f09
 
Introduction to OO Perl with Moose
Introduction to OO Perl with MooseIntroduction to OO Perl with Moose
Introduction to OO Perl with Moose
Dave Cross
 
YAPC::Asia 2014 - 半端なPHPDisでPHPerに陰で笑われないためのPerl Monger向け最新PHP事情
YAPC::Asia 2014 - 半端なPHPDisでPHPerに陰で笑われないためのPerl Monger向け最新PHP事情YAPC::Asia 2014 - 半端なPHPDisでPHPerに陰で笑われないためのPerl Monger向け最新PHP事情
YAPC::Asia 2014 - 半端なPHPDisでPHPerに陰で笑われないためのPerl Monger向け最新PHP事情
Junichi Ishida
 
Great Tools Heavily Used In Japan, You Don't Know.
Great Tools Heavily Used In Japan, You Don't Know.Great Tools Heavily Used In Japan, You Don't Know.
Great Tools Heavily Used In Japan, You Don't Know.
Junichi Ishida
 
Perl.Hacks.On.Vim
Perl.Hacks.On.VimPerl.Hacks.On.Vim
Perl.Hacks.On.VimLin Yo-An
 
10 books that every developer must read
10 books that every developer must read10 books that every developer must read
10 books that every developer must read
Ganesh Samarthyam
 
The Programmer
The ProgrammerThe Programmer
The Programmer
Kevlin Henney
 

Viewers also liked (12)

Java. Lecture 03. OOP and UML
Java. Lecture 03. OOP and UMLJava. Lecture 03. OOP and UML
Java. Lecture 03. OOP and UML
 
A very nice presentation on Moose.
A very nice presentation on Moose.A very nice presentation on Moose.
A very nice presentation on Moose.
 
Moose workshop
Moose workshopMoose workshop
Moose workshop
 
Firewall in Perl by Chankey Pathak
Firewall in Perl by Chankey PathakFirewall in Perl by Chankey Pathak
Firewall in Perl by Chankey Pathak
 
Moose Hacking Guide
Moose Hacking GuideMoose Hacking Guide
Moose Hacking Guide
 
Introduction to Perl MAGIC
Introduction to Perl MAGICIntroduction to Perl MAGIC
Introduction to Perl MAGIC
 
Introduction to OO Perl with Moose
Introduction to OO Perl with MooseIntroduction to OO Perl with Moose
Introduction to OO Perl with Moose
 
YAPC::Asia 2014 - 半端なPHPDisでPHPerに陰で笑われないためのPerl Monger向け最新PHP事情
YAPC::Asia 2014 - 半端なPHPDisでPHPerに陰で笑われないためのPerl Monger向け最新PHP事情YAPC::Asia 2014 - 半端なPHPDisでPHPerに陰で笑われないためのPerl Monger向け最新PHP事情
YAPC::Asia 2014 - 半端なPHPDisでPHPerに陰で笑われないためのPerl Monger向け最新PHP事情
 
Great Tools Heavily Used In Japan, You Don't Know.
Great Tools Heavily Used In Japan, You Don't Know.Great Tools Heavily Used In Japan, You Don't Know.
Great Tools Heavily Used In Japan, You Don't Know.
 
Perl.Hacks.On.Vim
Perl.Hacks.On.VimPerl.Hacks.On.Vim
Perl.Hacks.On.Vim
 
10 books that every developer must read
10 books that every developer must read10 books that every developer must read
10 books that every developer must read
 
The Programmer
The ProgrammerThe Programmer
The Programmer
 

Similar to Moose - YAPC::NA 2012

Perl object ?
Perl object ?Perl object ?
Perl object ?
ℕicolas ℝ.
 
Perl: Hate it for the Right Reasons
Perl: Hate it for the Right ReasonsPerl: Hate it for the Right Reasons
Perl: Hate it for the Right Reasons
Matt Follett
 
Lithium: The Framework for People Who Hate Frameworks
Lithium: The Framework for People Who Hate FrameworksLithium: The Framework for People Who Hate Frameworks
Lithium: The Framework for People Who Hate Frameworks
Nate Abele
 
Moose: Perl Objects
Moose: Perl ObjectsMoose: Perl Objects
Moose: Perl Objects
Lambert Lum
 
To infinity and beyond
To infinity and beyondTo infinity and beyond
To infinity and beyond
clintongormley
 
(Parameterized) Roles
(Parameterized) Roles(Parameterized) Roles
(Parameterized) Roles
sartak
 
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
 
Puppet and the HashiStack
Puppet and the HashiStackPuppet and the HashiStack
Puppet and the HashiStack
Bram Vogelaar
 
Perl Teach-In (part 2)
Perl Teach-In (part 2)Perl Teach-In (part 2)
Perl Teach-In (part 2)
Dave Cross
 
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 ...
Puppet
 
Replacing "exec" with a type and provider
Replacing "exec" with a type and providerReplacing "exec" with a type and provider
Replacing "exec" with a type and provider
Dominic Cleal
 
Stanford Hackathon - Puppet Modules
Stanford Hackathon - Puppet ModulesStanford Hackathon - Puppet Modules
Stanford Hackathon - Puppet Modules
Puppet
 
Rapid Development with Ruby/JRuby and Rails
Rapid Development with Ruby/JRuby and RailsRapid Development with Ruby/JRuby and Rails
Rapid Development with Ruby/JRuby and Railselliando dias
 
Postobjektové programovanie v Ruby
Postobjektové programovanie v RubyPostobjektové programovanie v Ruby
Postobjektové programovanie v Ruby
Jano Suchal
 
Reasons To Love Ruby
Reasons To Love RubyReasons To Love Ruby
Reasons To Love Ruby
Ben Scheirman
 
Ruby Programming Language
Ruby Programming LanguageRuby Programming Language
Ruby Programming Language
Duda Dornelles
 
A linguagem de programação Ruby - Robson "Duda" Sejan Soares Dornelles
A linguagem de programação Ruby - Robson "Duda" Sejan Soares DornellesA linguagem de programação Ruby - Robson "Duda" Sejan Soares Dornelles
A linguagem de programação Ruby - Robson "Duda" Sejan Soares Dornelles
Tchelinux
 
jRuby: The best of both worlds
jRuby: The best of both worldsjRuby: The best of both worlds
jRuby: The best of both worlds
Christopher Spring
 
DataMapper
DataMapperDataMapper
DataMapper
Yehuda Katz
 
The Zen of Lithium
The Zen of LithiumThe Zen of Lithium
The Zen of Lithium
Nate Abele
 

Similar to Moose - YAPC::NA 2012 (20)

Perl object ?
Perl object ?Perl object ?
Perl object ?
 
Perl: Hate it for the Right Reasons
Perl: Hate it for the Right ReasonsPerl: Hate it for the Right Reasons
Perl: Hate it for the Right Reasons
 
Lithium: The Framework for People Who Hate Frameworks
Lithium: The Framework for People Who Hate FrameworksLithium: The Framework for People Who Hate Frameworks
Lithium: The Framework for People Who Hate Frameworks
 
Moose: Perl Objects
Moose: Perl ObjectsMoose: Perl Objects
Moose: Perl Objects
 
To infinity and beyond
To infinity and beyondTo infinity and beyond
To infinity and beyond
 
(Parameterized) Roles
(Parameterized) Roles(Parameterized) Roles
(Parameterized) Roles
 
Good Evils In Perl (Yapc Asia)
Good Evils In Perl (Yapc Asia)Good Evils In Perl (Yapc Asia)
Good Evils In Perl (Yapc Asia)
 
Puppet and the HashiStack
Puppet and the HashiStackPuppet and the HashiStack
Puppet and the HashiStack
 
Perl Teach-In (part 2)
Perl Teach-In (part 2)Perl Teach-In (part 2)
Perl Teach-In (part 2)
 
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 ...
 
Replacing "exec" with a type and provider
Replacing "exec" with a type and providerReplacing "exec" with a type and provider
Replacing "exec" with a type and provider
 
Stanford Hackathon - Puppet Modules
Stanford Hackathon - Puppet ModulesStanford Hackathon - Puppet Modules
Stanford Hackathon - Puppet Modules
 
Rapid Development with Ruby/JRuby and Rails
Rapid Development with Ruby/JRuby and RailsRapid Development with Ruby/JRuby and Rails
Rapid Development with Ruby/JRuby and Rails
 
Postobjektové programovanie v Ruby
Postobjektové programovanie v RubyPostobjektové programovanie v Ruby
Postobjektové programovanie v Ruby
 
Reasons To Love Ruby
Reasons To Love RubyReasons To Love Ruby
Reasons To Love Ruby
 
Ruby Programming Language
Ruby Programming LanguageRuby Programming Language
Ruby Programming Language
 
A linguagem de programação Ruby - Robson "Duda" Sejan Soares Dornelles
A linguagem de programação Ruby - Robson "Duda" Sejan Soares DornellesA linguagem de programação Ruby - Robson "Duda" Sejan Soares Dornelles
A linguagem de programação Ruby - Robson "Duda" Sejan Soares Dornelles
 
jRuby: The best of both worlds
jRuby: The best of both worldsjRuby: The best of both worlds
jRuby: The best of both worlds
 
DataMapper
DataMapperDataMapper
DataMapper
 
The Zen of Lithium
The Zen of LithiumThe Zen of Lithium
The Zen of Lithium
 

More from xSawyer

do_this and die();
do_this and die();do_this and die();
do_this and die();
xSawyer
 
XS Fun
XS FunXS Fun
XS Fun
xSawyer
 
Asynchronous Programming FTW! 2 (with AnyEvent)
Asynchronous Programming FTW! 2 (with AnyEvent)Asynchronous Programming FTW! 2 (with AnyEvent)
Asynchronous Programming FTW! 2 (with AnyEvent)
xSawyer
 
Asynchronous programming FTW!
Asynchronous programming FTW!Asynchronous programming FTW!
Asynchronous programming FTW!
xSawyer
 
Our local state, my, my - Understanding Perl variables
Our local state, my, my - Understanding Perl variablesOur local state, my, my - Understanding Perl variables
Our local state, my, my - Understanding Perl variables
xSawyer
 
Your first website in under a minute with Dancer
Your first website in under a minute with DancerYour first website in under a minute with Dancer
Your first website in under a minute with Dancer
xSawyer
 
PerlDancer for Perlers (FOSDEM 2011)
PerlDancer for Perlers (FOSDEM 2011)PerlDancer for Perlers (FOSDEM 2011)
PerlDancer for Perlers (FOSDEM 2011)
xSawyer
 
Perl Dancer for Python programmers
Perl Dancer for Python programmersPerl Dancer for Python programmers
Perl Dancer for Python programmers
xSawyer
 
When Perl Met Android (YAPC::EU 2010)
When Perl Met Android (YAPC::EU 2010)When Perl Met Android (YAPC::EU 2010)
When Perl Met Android (YAPC::EU 2010)
xSawyer
 
Perl Dancer on Android (first attempt)
Perl Dancer on Android (first attempt)Perl Dancer on Android (first attempt)
Perl Dancer on Android (first attempt)
xSawyer
 
Source Code Management systems
Source Code Management systemsSource Code Management systems
Source Code Management systems
xSawyer
 
Red Flags in Programming
Red Flags in ProgrammingRed Flags in Programming
Red Flags in Programming
xSawyer
 

More from xSawyer (12)

do_this and die();
do_this and die();do_this and die();
do_this and die();
 
XS Fun
XS FunXS Fun
XS Fun
 
Asynchronous Programming FTW! 2 (with AnyEvent)
Asynchronous Programming FTW! 2 (with AnyEvent)Asynchronous Programming FTW! 2 (with AnyEvent)
Asynchronous Programming FTW! 2 (with AnyEvent)
 
Asynchronous programming FTW!
Asynchronous programming FTW!Asynchronous programming FTW!
Asynchronous programming FTW!
 
Our local state, my, my - Understanding Perl variables
Our local state, my, my - Understanding Perl variablesOur local state, my, my - Understanding Perl variables
Our local state, my, my - Understanding Perl variables
 
Your first website in under a minute with Dancer
Your first website in under a minute with DancerYour first website in under a minute with Dancer
Your first website in under a minute with Dancer
 
PerlDancer for Perlers (FOSDEM 2011)
PerlDancer for Perlers (FOSDEM 2011)PerlDancer for Perlers (FOSDEM 2011)
PerlDancer for Perlers (FOSDEM 2011)
 
Perl Dancer for Python programmers
Perl Dancer for Python programmersPerl Dancer for Python programmers
Perl Dancer for Python programmers
 
When Perl Met Android (YAPC::EU 2010)
When Perl Met Android (YAPC::EU 2010)When Perl Met Android (YAPC::EU 2010)
When Perl Met Android (YAPC::EU 2010)
 
Perl Dancer on Android (first attempt)
Perl Dancer on Android (first attempt)Perl Dancer on Android (first attempt)
Perl Dancer on Android (first attempt)
 
Source Code Management systems
Source Code Management systemsSource Code Management systems
Source Code Management systems
 
Red Flags in Programming
Red Flags in ProgrammingRed Flags in Programming
Red Flags in Programming
 

Recently uploaded

Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Tobias Schneck
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
Sri Ambati
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
ThousandEyes
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
Laura Byrne
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
Paul Groth
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
Cheryl Hung
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
91mobiles
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
Alan Dix
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
Safe Software
 
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Jeffrey Haguewood
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
DianaGray10
 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a button
DianaGray10
 
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
Product School
 
"Impact of front-end architecture on development cost", Viktor Turskyi
"Impact of front-end architecture on development cost", Viktor Turskyi"Impact of front-end architecture on development cost", Viktor Turskyi
"Impact of front-end architecture on development cost", Viktor Turskyi
Fwdays
 
PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)
Ralf Eggert
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
Product School
 
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Product School
 
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptxIOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
Abida Shariff
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
Jemma Hussein Allen
 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
OnBoard
 

Recently uploaded (20)

Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
 
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a button
 
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
 
"Impact of front-end architecture on development cost", Viktor Turskyi
"Impact of front-end architecture on development cost", Viktor Turskyi"Impact of front-end architecture on development cost", Viktor Turskyi
"Impact of front-end architecture on development cost", Viktor Turskyi
 
PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
 
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
 
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptxIOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
 

Moose - YAPC::NA 2012

  • 2. Sawyer X blogs.perl.org/users/sawyer_x search.cpan.org/~xsawyerx metacpan.org/author/XSAWYERX github.com/xsawyerx/ „The Dancer guy!“ Projects: Dancer, Module::Starter, MetaCPAN::API, MooseX::Role::Loggable, etc.
  • 3.
  • 4.
  • 6. … but why Moose? package Person; package User; use strict; use Email::Valid; use warnings; use Moose; use Moose::Util::TypeConstraints; use Carp qw( confess ); use DateTime; extends 'Person'; use DateTime::Format::Natural; subtype 'Email'     => as 'Str' sub new {     => where { Email::Valid­>address($_) }     my $class = shift;     => message { "$_ is not a valid email      my %p = ref $_[0] ? %{ $_[0] } : @_; address" };     exists $p{name} has email_address => (         or confess 'name is a required attribute';     is       => 'rw',     $class­>_validate_name( $p{name} );     isa      => 'Email',     required => 1,     exists $p{birth_date} );         or confess 'birth_date is a required attribute';     $p{birth_date} = $class­ >_coerce_birth_date( $p{birth_date} );     $class­>_validate_birth_date( $p{birth_date} );     $p{shirt_size} = 'l'         unless exists $p{shirt_size}:     $class­>_validate_shirt_size( $p{shirt_size} );     return bless %p, $class; } sub _validate_name {     shift;     my $name = shift;     local $Carp::CarpLevel = $Carp::CarpLevel + 1;     defined $name         or confess 'name must be a string'; }
  • 8. Writing objects in basic Perl 5 Create a reference (usually to a hash) Connect it to a package (using „bless“) Provide subroutines that access the hash keys Error check the hell out of it
  • 9. Writing objects in basic Perl 5, e.g. package Dog; use strict; use warnings; sub new { my $class = shift; my $self = bless {}, $class; return $self; } 1;
  • 10. Issues Defining the same new() concept every time No parameters for new() yet Will have to do all error-checking manually
  • 12. You get use strict; use warnings; new() method To hell with ponies, you get a moose! (roll picture of a moose beating a pony in soccer)
  • 13. Full affordance accessors (attributes) has name => ( is => 'rw' ); „ro“ is available for read-only attributes You can manually change setter/getter via writer/reader Attributes can have defaults Attributes can have type constraints Attributes can have traits Attributes can be lazy, have builders, clearers, predicates...
  • 14. Type constraints has name => ( is => 'ro', isa => 'Str' ); Str, Int, Bool, ArrayRef, HashRef, CodeRef, Regex, Classes Combine: ArrayRef|HashRef, ArrayRef[Str] Derivatives (Int is a Num) Create your own using subtype, available at Moose::Util::TypeConstraints
  • 15. Methods Same as before sub run { my $self = shift; say qq{I make it a habit only to run when being chased!}; }
  • 16. Inheritance easy as... package Punk use Moose; extends 'Person'; Multiple inheritance also possible (extends accepts array) package Child; use Moose; extends qw/Father Mother/;
  • 17. Roles are even better package Punk; use Moose; with qw/Tattoos Piercings Squatter/; Roles are things you do, instead of things you are.
  • 18. More hooks than a coat rack! package User::WinterAware; use Moose; extends 'User'; before leaving => sub { my $self = shift; $self->cold and $self->take_jacket; };
  • 19. More hooks than a coat rack! package User::Secure; use Moose; extends 'User'; around login => sub { my $orig = shift; my $self = shift; $self->security_check and $self->$orig(@_); };
  • 20. More hooks than a coat rack! Before After Around Inner Augment
  • 21. Back to attributes... has set => ( is => 'rw', isa => 'Set::Object', default => sub { Set::Object->new }, required => 1, lazy => 1, predicate => 'has_set', clearer => 'clear_set',
  • 22. Attribute options: default default => 'kitteh' # string default => 3 # number default => sub { {} } # HashRef default => sub { [] } # ArrayRef default => sub { Object->new } # an Object (if you need a more elaborate sub, use builder)
  • 23. Attribute options: required required => 1 # required required => 0 # not required
  • 24. Attribute options: lazy lazy => 1 # make it lazy Class will not create the slot for this attribute unless it absolutely has to, defined by whether it is accessed at all. No access? No penalty! Lazy == good
  • 25. Attribute options: builder builder => 'build_it' # subroutine name sub build_it { my $self = shift; # not a problem! return Some::Object->new( $self- >more_opts ); }
  • 26. Attribute options: clearer clearer => 'clear_it' # subroutine name # you don't need to create the subroutine sub time_machine { my $self = shift; $self->clear_it; # 'it' never happened :) }
  • 27. Attribute options: predicate predicate => 'has_it' # subroutine name # you don't need to create the subroutine sub try_to_do_it { my $self = shift; $self->has_it && $self->do_it(); }
  • 28. Attribute options: lazy_build lazy_build => 1 # <3 # the same as: lazy => 1, builder => '_build_it', # private clearer => 'clear_it', predicate => 'has_it',
  • 29. Example: Comican A hub for various comics strips Allow you to fetch comic strips Standard uniformed interface to add more comics We'll be using: Roles Lazy attributes Overriding attributes options Attribute predicates
  • 30. Comican comic modules Comican::Comic::Dilber t interface role Comican::Comic::PennyArcade Comican::Comic::xkcd Comican:: Role::Comic main module user Comican.pm
  • 31. Comican: overall Comican.pm is the user's interface It's a hub for Comican::Comic::* modules They are objects that fetch specific comic strips They have a common interface Defined by Comican::Role::Comic
  • 32. SHOW ME THE CODE!
  • 33. /^M(?:o(?:o|[ou]se)?)?$/ Moose: standart Mouse: subset, uses XS, faster (Any::Moose: use Mouse unless Moose already loaded) Moo: Pure-Perl, subset, blazing fast Mo: As little as possible (incl. character count) M: Really as little as possible Hummus (HuMoose): Incompatible chickpeas paste
  • 34.