in reply to Re: OO: how to make a generic sub (use roles or inheritance)
in thread OO: how to make a generic sub
tobyink++ really useful post. (You should think about putting several of your recent OO-related posts together into YAOO-Tutorial!)
I think its is worth noting that Roles can be simply implemented using basic Perl5 mechanisms (and with less loadtime/runtime costs):
#! perl-slw use strict; use 5.010; { package Roles::Jumper; ##requires "name"; sub import { my $caller = caller; { no strict; die "'name' method required" unless exists ${ "$caller\:\: +"}{name}; *{ "$caller\:\:jump" } = \&jump; } return; } sub jump { my $self = shift; say $self->name, " jumps!"; } } { package Pet::Dog; ##use Role::Tiny::With; ##with "Roles::Jumper"; #require Roles::Jumper; ## used if package in separate file Roles::Jumper->import; sub new { my $class = shift; bless {@_}, $class; } sub name { my $self = shift; return $self->{name}; } sub sound { my $self = shift; say $self->name, " says woof!"; } } { package Pet::Cat; ##use Role::Tiny::With; ##with "Roles::Jumper"; #require Roles::Jumper; ## used if package in separate file Roles::Jumper->import; sub new { my $class = shift; bless {@_}, $class; } sub name { my $self = shift; return $self->{name}; } sub sound { my $self = shift; say $self->name, " says meow!"; } } my $fido = Pet::Dog->new(name => "Fido"); $fido->jump; $fido->sound; my $felix = Pet::Cat->new(name => "Felix"); $felix->jump; $felix->sound; __END__ C:\test>roles.pl Fido jumps! Fido says woof! Felix jumps! Felix says meow!
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^3: OO: how to make a generic sub (use roles or inheritance)
by tobyink (Canon) on Jun 27, 2013 at 12:25 UTC | |
by BrowserUk (Patriarch) on Jun 27, 2013 at 20:45 UTC |