So instead of using roles wouldn’t it be nice if we could just do the following to an instantiated object:
$baz->add_singleton_method( legs => sub { 2 } );
Well if we define our Animal class like so then we can!
use MooseX::Declare;
class Animal {
method walk { "unknown" }
method wild { "wild?... I'm bliming livid!" }
method add_singleton_method( $method_name, $method ) {
my $singleton = $self->meta->create_anon_class(
superclasses => [ $self->meta->name ],
methods => { $method_name => $method },
);
$singleton->add_method( meta => sub { $singleton } );
$singleton->rebless_instance( $self );
}
}
This add_singleton_method does all the dirty work that applying a role to an object did in previous post.
To break this down:
my $singleton = $self->meta->create_anon_class(
superclasses => [ $self->meta->name ],
methods => { $method_name => $method },
);
This creates our anonymous class ($singleton). The “superclasses” part makes it a subclass of Animal and the “methods” part is where we add predefined methods (which we provide as args in add_singleton_methods)
$singleton->add_method( meta => sub { $singleton } );
Above adds the all important meta method. Without this then things can get a bit hairy!
$singleton->rebless_instance( $self );
This now reblesses the instance with this new anonymous class.
Now we can produce that singleton method like so:
my $baz = Animal->;new;
$baz->add_singleton_method( legs => sub { 2 } );
say $baz->legs; # => 2
And it all works in exactly same way as with role examples previously mentioned.
Now we can keep creating further anonymous subclasses by using add_singleton_method or you can just use Moose meta method to add more methods to current anonymous class:
$baz->meta->add_method( walk => sub { "when not drunk!" } );
Now if we tidy up the mechanics of all this into a Moose role with some extra fancy API:
NB. Think I’m safe from the Trade Description Act for my blog title over this role usage!)
package DoesSingletonMethod;
use Moose::Role;
our $singleton = sub {
my $self = shift;
my $methods = shift || {};
my $meta = $self->meta->create_anon_class(
superclasses => [ $self->meta->name ],
methods => $methods,
);
$meta->add_method( meta => sub { $meta } );
$meta->rebless_instance( $self );
};
sub become_singleton { $_[0]->$singleton }
sub add_singleton_method { $_[0]->$singleton({ $_[1] => $_[2] }) }
sub add_singleton_methods {
my $self = shift;
$self->$singleton({ @_ });
}
no Moose::Role;
1;
This nows means we can do the following:
use MooseX::Declare;
class Animal with DoesSingletonMethod {
method walk { "unknown" }
method wild { "wild?... I'm bliming livid!" }
}
# one way to create singleton method....
my $baz = Animal->new;
$baz->become_singleton; # make $baz a singleton
$baz->meta->add_method( baz => 'baz!' ); # add method "baz" using meta
# and another.....
my $foo = Animal->new;
$foo->add_singleton_method( foo => sub { 'foo!' } );
# and finally multiple methods....
my $bar = Animal->new;
$bar->add_singleton_methods(
bar1 => sub { 'bar1!' },
bar2 => sub { 'bar2!' },
);
Hmmm this is nice. Perhaps I’ll wrap this up as MooseX::SingletonMethod and upload to CPAN
Moritz Lenz mentions in his excellent Perlgeek.de blog that there is not enough pictures being used alongside posts in the Perl blogosphere.
Moritz is absolutely correct so I’ll make immediate amends by reproducing the core of my last post about how Moose Roles implemented singleton methods with some helpful diagrams.
So first here is the initial Animal class code again:
use MooseX::Declare;
class Animal {
method walk { "unknown" }
method wild { "wild?... I'm bliming livid!" }
}
my $baz = Animal->new;
Here is a diagram which shows the object ($baz) & each class with its methods:
From this we can see that:
- $baz is the instantiated object of the Animal class.
- The Animal class contains all the methods we defined (along with “new” & “meta”) and its superclass is Moose::Object.
NB. Moose::Object is the ultimate superclass which all Moose classes relate back to. In Moose::Object we can see all the base methods.
Next is the DoesHuman role and it being applied to the $baz object:
role DoesHuman {
method walk { "when not drunk!" }
method legs { 2 }
}
DoesHuman->meta->apply( $baz );
And finally this is how the class relationship now looks for $baz object after the above role was applied:

The anonymous class was created when the DoesHuman role was applied to $baz object and it now stands proudly at the front of the inheritance chain for $baz object.
Thus we have added singleton method(s) to an object by using Moose roles.
This is a clear example of a picture being definitely worth a thousand words
So following on from my last two posts (1)(2) about Moose Roles and Singleton Methods I thought it would be nice to know how Moose performs all this magic.
So to help explain all this I’ll create a simple (contrived!) example:
use MooseX::Declare;
class Animal {
method walk { "unknown" }
method wild { "wild?... I'm bliming livid!" }
}
Now if we introspect this:
my $baz = Animal->new; say "baz is an Animal and its " . $baz->walk . " if he can walk or not?"; say "baz methods are: ", join " | ", $baz->meta->get_method_list; say "baz ISA: ", join " | ", $baz->meta->class_precedence_list;
We will see this:
baz is an Animal and its unknown if he can walk or not?
baz methods are: walk | new | wild | meta
baz ISA: Animal | Moose::Object
Using get_method_list returns methods just in this class (running get_all_method_names would return all resolvable methods via inheritance).
And using class_precedence_list returns the class interitance chain starting with its own class Animal. NB. Moose::Object is the base class for all Moose objects.
So no surprises here. So what happens when I sprinkle some fairy dust on $baz by applying a role to this object (and creating a Singleton Method):
role DoesHuman {
method walk { "when not drunk!" }
method legs { 2 }
}
DoesHuman->meta->apply( $baz );
say "baz is now Human with " . $baz->legs . " legs and walks " . $baz->walk;
say "baz methods are: ", join " | ", $baz->meta->get_method_list;
say "baz ISA: ", join " | ", $baz->meta->class_precedence_list
say "baz says: ", $baz->wild;
This produces:
baz is now Human with 2 legs and walks when not drunk!
baz methods are: legs | walk | meta
baz ISA: Class::MOP::Class::__ANON__::SERIAL::2 | Animal | Moose::Object
baz says: wild?… I’m bliming livid!
First lets look at the object methods. legs has been added and walk has also nicely been replaced. So this does exactly what I asked it to do.
But hold on… where has wild gone from the method list? And yet when I do $self->wild it works fine??
Well if you followed Dave Thomas video link I gave in first post then this is easily explained (even though he’s talking about Ruby!).
If you look at the class inheritance you can see what happened. Here is my attempt to explain whats going on:
Applying DoesHuman role to $baz object has created new anonymous class called (in this instance) “Class::MOP::Class::__ANON__::SERIAL::2″ and puts the DoesHuman role methods legs and walk into there and then makes this class a child of Animal. $baz is then assigned (blessed) to this new anon class.
Or has Dave Thomas says:
move one to the right and then up one
But that only makes sense if you use same diagrams he had!
All very neat! In a nutshell its created a unique anonymous class with the role methods which $baz uses instead of the Animal class.
And you can keep adding to this anon class chaining:
role DoesMale {
method sex { "male" }
method wild { "nice to meet u!" }
}
DoesMale->meta->apply( $baz );
say "baz is now a " . $baz->sex;
say "baz methods are: ", join " | ", $baz->meta->get_method_list;
say "baz ISA: ", join " | ", $baz->meta->class_precedence_list;
say "baz says: ", $baz->wild;
baz is now a male
baz methods are: sex | wild | meta
baz ISA: Class::MOP::Class::__ANON__::SERIAL::3 | Class::MOP::Class::__ANON__::SERIAL::2 | Animal | Moose::Object
baz says: nice to meet u!
/I3az/
Some references:
If you feel that the “classic” Moose code in my last post seems a bit chunky when compared to the Ruby example then have a look at MooseX::Declare
MooseX::Declare cuts out the following boilerplate code from my previous Point example:
{
package Point;
use Moose;
...
no Moose;
__PACKAGE__->meta->make_immutable;
}
Down to just this:
use MooseX::Declare;
class Point {
...
}
Here is the first Point code & usage example using Moosex::Declare:
use MooseX::Declare;
class Point {
has x => ( isa => 'Int', is => 'rw' );
has y => ( isa => 'Int', is => 'rw' );
method negated { $self->new( x => -$self->x, y => -$self->y ) }
method transpose { $self->new( x => $self->y, y => $self->x ) }
method inspect { say $self->x . ' @ ' . $self->y }
}
my $p = Point->new( x => 4, y => 3 );
$p->negated->inspect; # => -4 @ -3
$p->transpose->inspect; # => 3 @ 4
role Negated {
requires 'transpose';
method negated { $self->transpose };
}
Negated->meta->apply( $p );
$p->negated->inspect; # => 3 @ 4
$p->transpose->inspect; # => 3 @ 4
Nice eh! Here is the second example of code transformed by MooseX::Declare:
use MooseX::Declare;
role DoesNegated {
method negated { $self->new( x => -$self->x, y => -$self->y ) }
}
role DoesTranspose {
method transpose { $self->new( x => $self->y, y => $self->x ) }
}
class Point with DoesNegated with DoesTranspose {
has x => ( isa => 'Int', is => 'rw' );
has y => ( isa => 'Int', is => 'rw' );
method inspect { say $self->x . ' @ ' . $self->y }
}
Then like in previous post to apply a role to object is just:
DoesTranspose->meta->apply( $p, alias => { transpose => 'negated' } );
Now if that doesn’t make you dribble then I don’t know what will
/I3az/
Randal Schwartz recently posted this bit of Smalltalk code on his Methods and Messages blog
p := 4 @ 3.
p changeClassTo: (p class copy superclass: p class).
p class methodDictionary at: #negated put: (p class methodDictionary at: #transpose).
p negated
My exposure to Smalltalk is limited to a quick look at Seaside web framework which is a bit like learning Rails instead of starting with Ruby
I can just about grok what this code does. Thankfully Rick DeNatale provided a nice Ruby conversion
Here is Rick’s subset of Smalltalk’s Point which replicates what the first Smalltalk line “p := 4 @ 3.” does:
class Point
attr_accessor :X, :y # :X should be lowercase but WordPress keeps converting it to a smiley!
def initialize(x, y)
@x, @y = x, y
end
def negated
self.class.new(-x, -y)
end
def transpose
self.class.new(y, x)
end
def inspect
"#{@x} @ #{@y}"
end
end
p = Point.new(4,3)
p.negated # => -4 @ -3
p.transpose # => 3 @ 4
So negated & transpose methods return new Point objects so all very straightforward so far.
In the Smalltalk code the object negated method gets amended to use the transpose method instead.
You can do this in Ruby by opening up the objects method like so:
def p.negated transpose end p.negated # => 3 @ 4 p.transpose # => 3 @ 4
Nice eh! The Ruby world refer to this has a Singleton Method. These are methods which are defined in the object and not the class.
I highly recommend watching this excellent video talk by Dave Thomas which provides excellent lucidity to how Ruby objects work.
Now how about Perl? I suspect you can use some MOP meta magic to do same but did you know that Moose Roles can be applied directly to objects?
Here’s is the Ruby Point code in Perl using classic Moose.
{
package Point;
use Moose;
has x => ( isa => 'Int', is => 'rw' );
has y => ( isa => 'Int', is => 'rw' );
sub negated {
my $self = shift;
$self->new( x => -$self->x, y => -$self->y );
}
sub transpose {
my $self = shift;
$self->new( x => $self->y, y => $self->x );
}
sub inspect { say "$_[0]->{x} \@ $_[0]->{y}" }
no Moose;
}
my $p = Point->new( x => 4, y => 3 );
$p->negated->inspect; # => -4 @ -3
$p->transpose->inspect; # => 3 @ 4
So all works same as the Ruby example. Now if we create a role like so:
{
package Negated;
use Moose::Role;
requires 'transpose';
sub negated {
my $self = shift;
$self->transpose;
}
no Moose::Role;
}
You can then “apply” it to any object like so:
Negated->meta->apply( $p ); $p->negated->inspect; # => 3 @ 4 $p->transpose->inspect; # => 3 @ 4
Lovely jubbly!
And as we’ve gone down this Moose Role route we might as well wrap it all up like this:
{
package Point;
use Moose;
with qw/DoesNegated DoesTranspose/;
has x => ( isa => 'Int', is => 'rw' );
has y => ( isa => 'Int', is => 'rw' );
sub inspect { say "$_[0]->{x} \@ $_[0]->{y}" }
no Moose;
}
{
package DoesNegated;
use Moose::Role;
sub negated {
my $self = shift;
$self->new( x => -$self->x, y => -$self->y );
}
no Moose::Role;
}
{
package DoesTranspose;
use Moose::Role;
sub transpose {
my $self = shift;
$self->new( x => $self->y, y => $self->x );
}
no Moose::Role;
}
my $p = Point->new( x => 4, y => 3 );
DoesTranspose->meta->apply( $p, alias => { transpose => 'negated' } );
$p->negated->inspect; # => 3 @ 4
$p->transpose->inspect; # => 3 @ 4
This time I used the “alias” option to rename the applied method on the Moose hoof
And u can keep applying roles to objects at your hearts content adding or replacing methods
as many times as u like.
/I3az/
Some references:
It may surprise you to know that I don’t normally go to search.cpan.org when I want to find something on CPAN.
Actually thats not totally true because I do use search.cpan.org but via CPANTools which provides a nice suggest dropdown as you type in the search textbox.
Another place I occasionally go to is KobeSearch but I prefer the standard CPAN look (a true design classic IMHO) to the uwinnipeg.ca one.
For something really shiny have a look at CPANTools Beta
/I3az/
Update: Nearly forgot this excellent custom Google search. Also note there is also a Perl custom search.
The CPAN upload RSS feed I subscribe to has been a bit quiet lately showing no uploads at this moment? This is a bit unusual because module uploads are normally constantly flowing onto CPAN.
So i checked my Google Reader settings and it had this strange RSS address…
http://unknownplace.org/cpanrecent/rss
Where did I get this from? Or did Google Reader insert this in at some point?? All very strange???
The site in question says its down for maintenance. Anyway I’ve updated my settings to use search.cpan.org RSS feed at….
Which translates into this feed….
http://search.cpan.org/uploads.rdf
Now happily seeing new uploads to CPAN
/I3az/
Tim Bunce posted about Perl Blogs last week talking in part about the sorry state of results
that comes from Google when you perform a “perl blog” search.
To help rectify this Tim has added the phrases “perl blog” & “perl programming” to his blog page.
I’ve also done the same to my sidebar and hopefully more Perl Blogs can follow Tim’s lead to help get rid of Google sickly results.
Of course there are additional motives behind all this. Now whether your concerned about Perl’s position in TIOBE results or not it is annoying that they have a few flaws in their processes which can paint a very inaccurate picture.
Clearly it is a concern to The Perl Foundation because Richdard Dice (President of TPF) in a recent interview in $foo magazine mentioned about opening up some dialogue with TIOBE.
Perhaps the TPF can do something about it. And we can also help by doing our little bit.
However more can be done. Here’s are some Google search results which you may find interesting….
site:cpan.org 1,070,000 results
site:cpan.org perl 495,000 results
site:cpan.org +"perl programming" 1260 results!
If I’m reading this correctly then only 0.12% of all the CPAN pages have the phrase “Perl Programming” in!
TIOBE use +”perl programming” in their searches. Now imagine if a phrase like….
CPAN – The Perl Programming Archive
was added to every page on CPAN
NB. And remember that CPAN pages are also mirrored on other websites!
I think it makes sense that every CPAN page is included by TIOBE in their analysis. If pages like these don’t show the popularity of a language then what does!
Bumping your TIOBE ratings like this isn’t new because do you recall the rise of Delphi from end of last year? Well this was due in part by the Delphi community making a similar concerted effort. Also it was due to fact of an emergence of a shiny new Google product and TIOBE having “Chrome” has part of the Delphi search criteria
/I3az/
PS. On a slightly related note I have also added a Perlsphere badge to this blogs sidebar.
And hot of the press after my last post about Vimeo I see that Piers Cawley has posted his excellent London.pm tech talk
Piers www.bofh.org.uk blog doesn’t look like its in any of the Perl planet feeds so I’ve attached his talk here. Enjoy!
An introduction to MooseX::Declare from Piers Cawley on Vimeo.
/I3az/
PS. I’ve also submitted Piers post to Hacker News to hopefully give it more publicity.
Came across a PostgreSQL channel on Vimeo the other day. This is a new channel containing video posts from the last PostgreSQL conference. Among them was a Perl talk by Matt Trout:
Perl Catalyst and DBIx::Class from Joshua Drake on Vimeo.
Matt comes to blows with the slideshow in above talk so you may prefer to watch a shortened version of this talk from the London Perl Workshop November 2008.
The slides can be found on Shadowcat’s website (requires Firefox).
More Perl videos are available though this tag does mix in some non related stuff but you can watch Giles Bowkett attempt:
Lightbulb Joke: Perl from giles goat boy on Vimeo.
or instead watch something that is really funny: 
YAPC::EU Promo from Curtis Poe on Vimeo.
/I3az/
PS. I did try embedded the vimeo videos in post but WordPress decided to spit them out and just leave the placeholders ;-(
PPS. Now fixed! Use (vimeo ####) where #### is the video id from the vimeo URL and replace parenthesis with square brackets!




