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 - YAPC::NA 2012
Moose - YAPC::NA 2012
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
Moose - YAPC::NA 2012
Thank you.

More Related Content

What's hot (20)

Introduction To Moose
Introduction To MooseIntroduction To Moose
Introduction To Moose
Mike Whitaker
 
CoffeeScript
CoffeeScriptCoffeeScript
CoffeeScript
None
 
Introduction to CoffeeScript
Introduction to CoffeeScriptIntroduction to CoffeeScript
Introduction to CoffeeScript
Stalin Thangaraj
 
Coffee Script
Coffee ScriptCoffee Script
Coffee Script
Michal Taberski
 
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 CodeIgniter
CodeIgniter 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 Perl
Kang-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
Perl
RaviShankar695257
 
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
 
Introduction To Moose
Introduction To MooseIntroduction To Moose
Introduction To Moose
Mike Whitaker
 
CoffeeScript
CoffeeScriptCoffeeScript
CoffeeScript
None
 
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 CodeIgniter
CodeIgniter 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
 
Good Evils In Perl
Good Evils In PerlGood Evils In Perl
Good Evils In Perl
Kang-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
 
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
 

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
colriot
 
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.Vim
Lin 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
 
Java. Lecture 03. OOP and UML
Java. Lecture 03. OOP and UMLJava. Lecture 03. OOP and UML
Java. Lecture 03. OOP and UML
colriot
 
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.Vim
Lin 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
 

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

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
Replacing "exec" with a type and providerReplacing "exec" with a type and provider
Replacing "exec" with a type and provider
Dominic Cleal
 
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
 
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 Rails
elliando 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
 
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
 
Ruby Programming Language
Ruby Programming LanguageRuby Programming Language
Ruby Programming Language
Duda Dornelles
 
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
 
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
Replacing "exec" with a type and providerReplacing "exec" with a type and provider
Replacing "exec" with a type and provider
Dominic Cleal
 
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
 
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 Rails
elliando 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
 
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
 
Ruby Programming Language
Ruby Programming LanguageRuby Programming Language
Ruby Programming Language
Duda Dornelles
 
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
 
The Zen of Lithium
The Zen of LithiumThe Zen of Lithium
The Zen of Lithium
Nate Abele
 

More from xSawyer (12)

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
 
do_this and die();
do_this and die();do_this and die();
do_this and die();
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
 

Recently uploaded (20)

Buckeye Dreamin 2024: Assessing and Resolving Technical Debt
Buckeye Dreamin 2024: Assessing and Resolving Technical DebtBuckeye Dreamin 2024: Assessing and Resolving Technical Debt
Buckeye Dreamin 2024: Assessing and Resolving Technical Debt
Lynda Kane
 
Build Your Own Copilot & Agents For Devs
Build Your Own Copilot & Agents For DevsBuild Your Own Copilot & Agents For Devs
Build Your Own Copilot & Agents For Devs
Brian McKeiver
 
tecnologias de las primeras civilizaciones.pdf
tecnologias de las primeras civilizaciones.pdftecnologias de las primeras civilizaciones.pdf
tecnologias de las primeras civilizaciones.pdf
fjgm517
 
Image processinglab image processing image processing
Image processinglab image processing  image processingImage processinglab image processing  image processing
Image processinglab image processing image processing
RaghadHany
 
Asthma presentación en inglés abril 2025 pdf
Asthma presentación en inglés abril 2025 pdfAsthma presentación en inglés abril 2025 pdf
Asthma presentación en inglés abril 2025 pdf
VanessaRaudez
 
Linux Professional Institute LPIC-1 Exam.pdf
Linux Professional Institute LPIC-1 Exam.pdfLinux Professional Institute LPIC-1 Exam.pdf
Linux Professional Institute LPIC-1 Exam.pdf
RHCSA Guru
 
Network Security. Different aspects of Network Security.
Network Security. Different aspects of Network Security.Network Security. Different aspects of Network Security.
Network Security. Different aspects of Network Security.
gregtap1
 
Automation Hour 1/28/2022: Capture User Feedback from Anywhere
Automation Hour 1/28/2022: Capture User Feedback from AnywhereAutomation Hour 1/28/2022: Capture User Feedback from Anywhere
Automation Hour 1/28/2022: Capture User Feedback from Anywhere
Lynda Kane
 
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
SOFTTECHHUB
 
Big Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur MorganBig Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur Morgan
Arthur Morgan
 
"Client Partnership — the Path to Exponential Growth for Companies Sized 50-5...
"Client Partnership — the Path to Exponential Growth for Companies Sized 50-5..."Client Partnership — the Path to Exponential Growth for Companies Sized 50-5...
"Client Partnership — the Path to Exponential Growth for Companies Sized 50-5...
Fwdays
 
Technology Trends in 2025: AI and Big Data Analytics
Technology Trends in 2025: AI and Big Data AnalyticsTechnology Trends in 2025: AI and Big Data Analytics
Technology Trends in 2025: AI and Big Data Analytics
InData Labs
 
Dev Dives: Automate and orchestrate your processes with UiPath Maestro
Dev Dives: Automate and orchestrate your processes with UiPath MaestroDev Dives: Automate and orchestrate your processes with UiPath Maestro
Dev Dives: Automate and orchestrate your processes with UiPath Maestro
UiPathCommunity
 
ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes Partner Innovation Updates for May 2025ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes
 
Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)
Ortus Solutions, Corp
 
Rusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond SparkRusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond Spark
carlyakerly1
 
Role of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered ManufacturingRole of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered Manufacturing
Andrew Leo
 
Procurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptxProcurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptx
Jon Hansen
 
Cyber Awareness overview for 2025 month of security
Cyber Awareness overview for 2025 month of securityCyber Awareness overview for 2025 month of security
Cyber Awareness overview for 2025 month of security
riccardosl1
 
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptxSpecial Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
shyamraj55
 
Buckeye Dreamin 2024: Assessing and Resolving Technical Debt
Buckeye Dreamin 2024: Assessing and Resolving Technical DebtBuckeye Dreamin 2024: Assessing and Resolving Technical Debt
Buckeye Dreamin 2024: Assessing and Resolving Technical Debt
Lynda Kane
 
Build Your Own Copilot & Agents For Devs
Build Your Own Copilot & Agents For DevsBuild Your Own Copilot & Agents For Devs
Build Your Own Copilot & Agents For Devs
Brian McKeiver
 
tecnologias de las primeras civilizaciones.pdf
tecnologias de las primeras civilizaciones.pdftecnologias de las primeras civilizaciones.pdf
tecnologias de las primeras civilizaciones.pdf
fjgm517
 
Image processinglab image processing image processing
Image processinglab image processing  image processingImage processinglab image processing  image processing
Image processinglab image processing image processing
RaghadHany
 
Asthma presentación en inglés abril 2025 pdf
Asthma presentación en inglés abril 2025 pdfAsthma presentación en inglés abril 2025 pdf
Asthma presentación en inglés abril 2025 pdf
VanessaRaudez
 
Linux Professional Institute LPIC-1 Exam.pdf
Linux Professional Institute LPIC-1 Exam.pdfLinux Professional Institute LPIC-1 Exam.pdf
Linux Professional Institute LPIC-1 Exam.pdf
RHCSA Guru
 
Network Security. Different aspects of Network Security.
Network Security. Different aspects of Network Security.Network Security. Different aspects of Network Security.
Network Security. Different aspects of Network Security.
gregtap1
 
Automation Hour 1/28/2022: Capture User Feedback from Anywhere
Automation Hour 1/28/2022: Capture User Feedback from AnywhereAutomation Hour 1/28/2022: Capture User Feedback from Anywhere
Automation Hour 1/28/2022: Capture User Feedback from Anywhere
Lynda Kane
 
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
SOFTTECHHUB
 
Big Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur MorganBig Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur Morgan
Arthur Morgan
 
"Client Partnership — the Path to Exponential Growth for Companies Sized 50-5...
"Client Partnership — the Path to Exponential Growth for Companies Sized 50-5..."Client Partnership — the Path to Exponential Growth for Companies Sized 50-5...
"Client Partnership — the Path to Exponential Growth for Companies Sized 50-5...
Fwdays
 
Technology Trends in 2025: AI and Big Data Analytics
Technology Trends in 2025: AI and Big Data AnalyticsTechnology Trends in 2025: AI and Big Data Analytics
Technology Trends in 2025: AI and Big Data Analytics
InData Labs
 
Dev Dives: Automate and orchestrate your processes with UiPath Maestro
Dev Dives: Automate and orchestrate your processes with UiPath MaestroDev Dives: Automate and orchestrate your processes with UiPath Maestro
Dev Dives: Automate and orchestrate your processes with UiPath Maestro
UiPathCommunity
 
ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes Partner Innovation Updates for May 2025ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes
 
Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)
Ortus Solutions, Corp
 
Rusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond SparkRusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond Spark
carlyakerly1
 
Role of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered ManufacturingRole of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered Manufacturing
Andrew Leo
 
Procurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptxProcurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptx
Jon Hansen
 
Cyber Awareness overview for 2025 month of security
Cyber Awareness overview for 2025 month of securityCyber Awareness overview for 2025 month of security
Cyber Awareness overview for 2025 month of security
riccardosl1
 
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptxSpecial Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
shyamraj55
 

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.
  • 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