SlideShare a Scribd company logo
Moose A postmodern metaclass-based object system for Perl 5
Moose Sawyer X * blogs.perl.org/users/sawyer_x *  search.cpan.org/~xsawyerx/ * search.metacpan.org/#/author/XSAWYERX * github.com/xsawyerx
Objects in Perl 5 (a short intro) A blessed hashref
Manual  new()  method
No real attributes bless {}, __PACKAGE__; sub new { my ( $class, @args ) =  @_; my $self = { @args }; # params bless $self, $class; return $self; } sub name { my ( $self, $name ) = @_; $name and $self->{'name'} = $name; return $self->{'name'}; }
Why would you want to use Moose? Moose package Person; use strict; use warnings; use Carp qw( confess ); use DateTime; use DateTime::Format::Natural; sub new { my $class = shift; my %p = ref $_[0] ? %{ $_[0] } : @_; exists $p{name} or confess 'name is a required attribute'; $class->_validate_name( $p{name} ); 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'; } Plain old Perl 5 package User; use Email::Valid; use Moose; use Moose::Util::TypeConstraints; extends 'Person'; subtype 'Email' => as 'Str' => where { Email::Valid->address($_) } => message { "$_ is not a valid email address" }; has email_address => ( is  => 'rw', isa  => 'Email', required => 1, );
Get it?
Defining an object in Moose use strict
use warnings
An object!
new()  method
A pon-.. err.. a moose! package User; use Moose; 1; You get:
Full-Affordance accessors ' ro ' is also available for read-only attributes!
You can set the getter or setter manually via  reader / writer
I'll show more attribute options later on has name => ( is => 'rw', );
An attribute with type constraint Lots of types:  Str ,  Int ,  ArrayRef ,  HashRef ,  CodeRef ,  Regexp
You can combine:  ArrayRef[Str] ,  HashRef[ArrayRef[Int]]
They have inheritance:  Int  is a  Num
Roll your own using  subtype package User; use Moose; has name => ( is  => 'rw', isa => 'Str', ); 1;
Methods are the same as before sub method { my $self = shift; ... $self->more(); }
Inheritance is as easy as... Multiple inheritance is also possible,  extends  accepts an array package Punk; use Moose; extends 'Person'; 1; package Child; use Moose; extends qw/ Father Mother /; 1;
Roles are even easier! Multiple roles are recommend!  with  accepts an array too package Punk; use Moose; extends 'Person'; with 'Piercings'; 1; package Punk; use Moose; extends 'Person'; with qw/ Piercings Tattoos /; 1;
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; }; 1; before

More Related Content

What's hot (20)

PDF
Moose workshop
Ynon Perek
 
PDF
WordPress Cuztom Helper
slicejack
 
PDF
To infinity and beyond
clintongormley
 
PDF
DBIx::Class beginners
leo lapworth
 
PDF
DBIx::Class introduction - 2010
leo lapworth
 
PDF
Doctrine MongoDB ODM (PDXPHP)
Kris Wallsmith
 
PDF
The effective use of Django ORM
Yaroslav Muravskyi
 
PDF
The jQuery Divide
Rebecca Murphey
 
PDF
Django - 次の一歩 gumiStudy#3
makoto tsuyuki
 
PDF
A Few of My Favorite (Python) Things
Michael Pirnat
 
PDF
From mysql to MongoDB(MongoDB2011北京交流会)
Night Sailer
 
KEY
Keeping It Small with Slim
Raven Tools
 
KEY
Introduction to Perl Best Practices
José Castro
 
PDF
WordPress London 16 May 2012 - You don’t know query
l3rady
 
PDF
Puppet Camp DC 2015: Stop Writing Puppet Modules: A Guide to Best Practices i...
Puppet
 
PDF
Introducing Assetic (NYPHP)
Kris Wallsmith
 
PDF
Advanced symfony Techniques
Kris Wallsmith
 
PPTX
Bioinformatics p5-bioperl v2013-wim_vancriekinge
Prof. Wim Van Criekinge
 
PPTX
Bioinformatica p6-bioperl
Prof. Wim Van Criekinge
 
PPT
Ant
sundar22in
 
Moose workshop
Ynon Perek
 
WordPress Cuztom Helper
slicejack
 
To infinity and beyond
clintongormley
 
DBIx::Class beginners
leo lapworth
 
DBIx::Class introduction - 2010
leo lapworth
 
Doctrine MongoDB ODM (PDXPHP)
Kris Wallsmith
 
The effective use of Django ORM
Yaroslav Muravskyi
 
The jQuery Divide
Rebecca Murphey
 
Django - 次の一歩 gumiStudy#3
makoto tsuyuki
 
A Few of My Favorite (Python) Things
Michael Pirnat
 
From mysql to MongoDB(MongoDB2011北京交流会)
Night Sailer
 
Keeping It Small with Slim
Raven Tools
 
Introduction to Perl Best Practices
José Castro
 
WordPress London 16 May 2012 - You don’t know query
l3rady
 
Puppet Camp DC 2015: Stop Writing Puppet Modules: A Guide to Best Practices i...
Puppet
 
Introducing Assetic (NYPHP)
Kris Wallsmith
 
Advanced symfony Techniques
Kris Wallsmith
 
Bioinformatics p5-bioperl v2013-wim_vancriekinge
Prof. Wim Van Criekinge
 
Bioinformatica p6-bioperl
Prof. Wim Van Criekinge
 

Similar to Moose talk at FOSDEM 2011 (Perl devroom) (20)

ODP
Moose - YAPC::NA 2012
xSawyer
 
ODP
Perl Teach-In (part 2)
Dave Cross
 
PDF
Perl object ?
ℕicolas ℝ.
 
ODP
Object-Oriented Programming with Perl and Moose
Dave Cross
 
KEY
Extending Moose
sartak
 
ODP
Moose: Perl Objects
Lambert Lum
 
ODP
Modern Perl
Marcos Rebelo
 
ODP
use Moose; &focus_on_actual_problem_solving
Rafiq Gemmail
 
PDF
Method::Signatures
Michael Schwern
 
PDF
P6 OO vs Moose (&Moo)
lichtkind
 
PDF
Introduction to OO Perl with Moose
Dave Cross
 
PPTX
Moo the universe and everything
Henry Van Styn
 
ODP
Modern Perl
Dave Cross
 
PDF
Moo at System::Image::Update
Jens Rehsack
 
PDF
Perl6 signatures, types and multicall
Simon Proctor
 
PDF
Modern Web Development in Perl
Jason Crome
 
ODP
Perl Teach-In (part 1)
Dave Cross
 
PPTX
Marcs (bio)perl course
BITS
 
PPT
Perl from the ground up: objects and testing
Shmuel Fomberg
 
ODP
Владимир Перепелица "Модули"
Media Gorod
 
Moose - YAPC::NA 2012
xSawyer
 
Perl Teach-In (part 2)
Dave Cross
 
Perl object ?
ℕicolas ℝ.
 
Object-Oriented Programming with Perl and Moose
Dave Cross
 
Extending Moose
sartak
 
Moose: Perl Objects
Lambert Lum
 
Modern Perl
Marcos Rebelo
 
use Moose; &focus_on_actual_problem_solving
Rafiq Gemmail
 
Method::Signatures
Michael Schwern
 
P6 OO vs Moose (&Moo)
lichtkind
 
Introduction to OO Perl with Moose
Dave Cross
 
Moo the universe and everything
Henry Van Styn
 
Modern Perl
Dave Cross
 
Moo at System::Image::Update
Jens Rehsack
 
Perl6 signatures, types and multicall
Simon Proctor
 
Modern Web Development in Perl
Jason Crome
 
Perl Teach-In (part 1)
Dave Cross
 
Marcs (bio)perl course
BITS
 
Perl from the ground up: objects and testing
Shmuel Fomberg
 
Владимир Перепелица "Модули"
Media Gorod
 
Ad

More from xSawyer (12)

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

Recently uploaded (20)

PDF
LLMs.txt: Easily Control How AI Crawls Your Site
Keploy
 
PDF
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 
PDF
CIFDAQ Weekly Market Wrap for 11th July 2025
CIFDAQ
 
PDF
Newgen Beyond Frankenstein_Build vs Buy_Digital_version.pdf
darshakparmar
 
PDF
Timothy Rottach - Ramp up on AI Use Cases, from Vector Search to AI Agents wi...
AWS Chicago
 
PDF
Building Real-Time Digital Twins with IBM Maximo & ArcGIS Indoors
Safe Software
 
PPTX
AUTOMATION AND ROBOTICS IN PHARMA INDUSTRY.pptx
sameeraaabegumm
 
PDF
Complete JavaScript Notes: From Basics to Advanced Concepts.pdf
haydendavispro
 
PDF
Blockchain Transactions Explained For Everyone
CIFDAQ
 
PDF
July Patch Tuesday
Ivanti
 
PDF
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
PDF
Jak MŚP w Europie Środkowo-Wschodniej odnajdują się w świecie AI
dominikamizerska1
 
PDF
Transcript: New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
PPTX
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
PPTX
UiPath Academic Alliance Educator Panels: Session 2 - Business Analyst Content
DianaGray10
 
PDF
New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
PDF
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
PDF
Exolore The Essential AI Tools in 2025.pdf
Srinivasan M
 
PPTX
OpenID AuthZEN - Analyst Briefing July 2025
David Brossard
 
PDF
Smart Trailers 2025 Update with History and Overview
Paul Menig
 
LLMs.txt: Easily Control How AI Crawls Your Site
Keploy
 
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 
CIFDAQ Weekly Market Wrap for 11th July 2025
CIFDAQ
 
Newgen Beyond Frankenstein_Build vs Buy_Digital_version.pdf
darshakparmar
 
Timothy Rottach - Ramp up on AI Use Cases, from Vector Search to AI Agents wi...
AWS Chicago
 
Building Real-Time Digital Twins with IBM Maximo & ArcGIS Indoors
Safe Software
 
AUTOMATION AND ROBOTICS IN PHARMA INDUSTRY.pptx
sameeraaabegumm
 
Complete JavaScript Notes: From Basics to Advanced Concepts.pdf
haydendavispro
 
Blockchain Transactions Explained For Everyone
CIFDAQ
 
July Patch Tuesday
Ivanti
 
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
Jak MŚP w Europie Środkowo-Wschodniej odnajdują się w świecie AI
dominikamizerska1
 
Transcript: New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
UiPath Academic Alliance Educator Panels: Session 2 - Business Analyst Content
DianaGray10
 
New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
Exolore The Essential AI Tools in 2025.pdf
Srinivasan M
 
OpenID AuthZEN - Analyst Briefing July 2025
David Brossard
 
Smart Trailers 2025 Update with History and Overview
Paul Menig
 

Moose talk at FOSDEM 2011 (Perl devroom)

  • 1. Moose A postmodern metaclass-based object system for Perl 5
  • 2. Moose Sawyer X * blogs.perl.org/users/sawyer_x * search.cpan.org/~xsawyerx/ * search.metacpan.org/#/author/XSAWYERX * github.com/xsawyerx
  • 3. Objects in Perl 5 (a short intro) A blessed hashref
  • 4. Manual new() method
  • 5. No real attributes bless {}, __PACKAGE__; sub new { my ( $class, @args ) = @_; my $self = { @args }; # params bless $self, $class; return $self; } sub name { my ( $self, $name ) = @_; $name and $self->{'name'} = $name; return $self->{'name'}; }
  • 6. Why would you want to use Moose? Moose package Person; use strict; use warnings; use Carp qw( confess ); use DateTime; use DateTime::Format::Natural; sub new { my $class = shift; my %p = ref $_[0] ? %{ $_[0] } : @_; exists $p{name} or confess 'name is a required attribute'; $class->_validate_name( $p{name} ); 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'; } Plain old Perl 5 package User; use Email::Valid; use Moose; use Moose::Util::TypeConstraints; extends 'Person'; subtype 'Email' => as 'Str' => where { Email::Valid->address($_) } => message { "$_ is not a valid email address" }; has email_address => ( is => 'rw', isa => 'Email', required => 1, );
  • 8. Defining an object in Moose use strict
  • 12. A pon-.. err.. a moose! package User; use Moose; 1; You get:
  • 13. Full-Affordance accessors ' ro ' is also available for read-only attributes!
  • 14. You can set the getter or setter manually via reader / writer
  • 15. I'll show more attribute options later on has name => ( is => 'rw', );
  • 16. An attribute with type constraint Lots of types: Str , Int , ArrayRef , HashRef , CodeRef , Regexp
  • 17. You can combine: ArrayRef[Str] , HashRef[ArrayRef[Int]]
  • 18. They have inheritance: Int is a Num
  • 19. Roll your own using subtype package User; use Moose; has name => ( is => 'rw', isa => 'Str', ); 1;
  • 20. Methods are the same as before sub method { my $self = shift; ... $self->more(); }
  • 21. Inheritance is as easy as... Multiple inheritance is also possible, extends accepts an array package Punk; use Moose; extends 'Person'; 1; package Child; use Moose; extends qw/ Father Mother /; 1;
  • 22. Roles are even easier! Multiple roles are recommend! with accepts an array too package Punk; use Moose; extends 'Person'; with 'Piercings'; 1; package Punk; use Moose; extends 'Person'; with qw/ Piercings Tattoos /; 1;
  • 23. 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; }; 1; before
  • 24. after
  • 25. 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(@_); }; 1; before
  • 26. after
  • 28. inner
  • 30. Back to attributes options... has set => ( is => 'rw', isa => 'Set::Object', default => sub { Set::Object->new }, required => 1, lazy => 1, predicate => 'has_set', clearer => 'clear_set', builder => 'build_set', );
  • 31. Attribute options default => 'kitteh', # string default => 3, # number default => sub { {} }, # HashRef default => sub { [] }, # ArrayRef default => sub { Object->new }, # an Object etc. etc. (if you need a more elaborate sub, use builder ) default
  • 32. Attribute options required => 1, # required required => 0, # not required required
  • 33. Attribute options lazy => 1, # make it lazy Class will not create the slot for this attribute unless it absolutely has to. That is defined by whether it is accessed at all. Wasn't accessed? You don't pay the penalty! :) lazy = good lazy
  • 34. Attribute options builder => 'build_it', # subroutine name sub build_it { my $self = shift; # not a problem! return Some::Object->new( $self->more_opts, ); } # and, obviously... after build_it => sub { “they will come” }; (a builder sets the value of the attribute) builder
  • 35. Attribute options 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 :) } (a clearer clears the value, as if it never existed) (does not go back to default) clearer
  • 36. Attribute options 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(); } (a predicate checks an attribute value exists) (even false values) (which is good!) predicate
  • 37. Attribute options lazy_build => 1, # <3 # the same as: lazy => 1, builder => '_build_it', # private clearer => 'clear_it', predicate => 'has_it', ( lazy_build is recommended) lazy_build
  • 41. It's here to stay
  • 42. Check it out! A ton more options
  • 50. ... sub { goto CPAN; }