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

PDF
OO Perl with Moose
KEY
Intro To Moose
ODP
Moose (Perl 5)
PPTX
Moose Best Practices
KEY
Introduction To Moose
PDF
Introduction to Moose
ODP
Evolving Software with Moose
OO Perl with Moose
Intro To Moose
Moose (Perl 5)
Moose Best Practices
Introduction To Moose
Introduction to Moose
Evolving Software with Moose

What's hot (20)

PDF
Moose workshop
PDF
WordPress Cuztom Helper
PDF
To infinity and beyond
PDF
DBIx::Class beginners
PDF
DBIx::Class introduction - 2010
PDF
Doctrine MongoDB ODM (PDXPHP)
PDF
The effective use of Django ORM
PDF
The jQuery Divide
PDF
Django - 次の一歩 gumiStudy#3
PDF
A Few of My Favorite (Python) Things
PDF
From mysql to MongoDB(MongoDB2011北京交流会)
KEY
Keeping It Small with Slim
KEY
Introduction to Perl Best Practices
PDF
WordPress London 16 May 2012 - You don’t know query
PDF
Puppet Camp DC 2015: Stop Writing Puppet Modules: A Guide to Best Practices i...
PDF
Introducing Assetic (NYPHP)
PDF
Advanced symfony Techniques
PPTX
Bioinformatics p5-bioperl v2013-wim_vancriekinge
PPTX
Bioinformatica p6-bioperl
PPT
Moose workshop
WordPress Cuztom Helper
To infinity and beyond
DBIx::Class beginners
DBIx::Class introduction - 2010
Doctrine MongoDB ODM (PDXPHP)
The effective use of Django ORM
The jQuery Divide
Django - 次の一歩 gumiStudy#3
A Few of My Favorite (Python) Things
From mysql to MongoDB(MongoDB2011北京交流会)
Keeping It Small with Slim
Introduction to Perl Best Practices
WordPress London 16 May 2012 - You don’t know query
Puppet Camp DC 2015: Stop Writing Puppet Modules: A Guide to Best Practices i...
Introducing Assetic (NYPHP)
Advanced symfony Techniques
Bioinformatics p5-bioperl v2013-wim_vancriekinge
Bioinformatica p6-bioperl
Ad

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

ODP
Moose - YAPC::NA 2012
ODP
Perl Teach-In (part 2)
PDF
Perl object ?
ODP
Object-Oriented Programming with Perl and Moose
KEY
Extending Moose
ODP
Moose: Perl Objects
ODP
Modern Perl
ODP
use Moose; &focus_on_actual_problem_solving
PDF
Method::Signatures
PDF
P6 OO vs Moose (&Moo)
PDF
Introduction to OO Perl with Moose
PPTX
Moo the universe and everything
ODP
Modern Perl
PDF
Moo at System::Image::Update
PDF
Perl6 signatures, types and multicall
PDF
Modern Web Development in Perl
ODP
Perl Teach-In (part 1)
PPTX
Marcs (bio)perl course
PPT
Perl from the ground up: objects and testing
ODP
Владимир Перепелица "Модули"
Moose - YAPC::NA 2012
Perl Teach-In (part 2)
Perl object ?
Object-Oriented Programming with Perl and Moose
Extending Moose
Moose: Perl Objects
Modern Perl
use Moose; &focus_on_actual_problem_solving
Method::Signatures
P6 OO vs Moose (&Moo)
Introduction to OO Perl with Moose
Moo the universe and everything
Modern Perl
Moo at System::Image::Update
Perl6 signatures, types and multicall
Modern Web Development in Perl
Perl Teach-In (part 1)
Marcs (bio)perl course
Perl from the ground up: objects and testing
Владимир Перепелица "Модули"
Ad

More from xSawyer (12)

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

Recently uploaded (20)

PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
PPTX
Cloud computing and distributed systems.
PDF
Encapsulation theory and applications.pdf
PPTX
Understanding_Digital_Forensics_Presentation.pptx
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PPTX
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
PPTX
MYSQL Presentation for SQL database connectivity
PDF
Machine learning based COVID-19 study performance prediction
DOCX
The AUB Centre for AI in Media Proposal.docx
PDF
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
PDF
Review of recent advances in non-invasive hemoglobin estimation
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PPTX
ACSFv1EN-58255 AWS Academy Cloud Security Foundations.pptx
PDF
KodekX | Application Modernization Development
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PDF
Empathic Computing: Creating Shared Understanding
PPTX
sap open course for s4hana steps from ECC to s4
PDF
Unlocking AI with Model Context Protocol (MCP)
Mobile App Security Testing_ A Comprehensive Guide.pdf
Digital-Transformation-Roadmap-for-Companies.pptx
Cloud computing and distributed systems.
Encapsulation theory and applications.pdf
Understanding_Digital_Forensics_Presentation.pptx
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
MYSQL Presentation for SQL database connectivity
Machine learning based COVID-19 study performance prediction
The AUB Centre for AI in Media Proposal.docx
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
Review of recent advances in non-invasive hemoglobin estimation
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
ACSFv1EN-58255 AWS Academy Cloud Security Foundations.pptx
KodekX | Application Modernization Development
Agricultural_Statistics_at_a_Glance_2022_0.pdf
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
Empathic Computing: Creating Shared Understanding
sap open course for s4hana steps from ECC to s4
Unlocking AI with Model Context Protocol (MCP)

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; }