Object::Method - attach method to objects instead of classes.
package Stuff; use Object::Method; package main; my $o = Stuff->new; my $p = Stuff->new; # Attach method 'foo' to $o but not $p $o->method("foo", sub { ... });
Object::Method lets you attach methods to methods to object but not its classes. There are three different ways to use this module. Keep reading.
The first way is to use it to create a class that allows user to attach methods at runtime. To do this, simply put 'use Object::Method' in your class body like this:
package Stuff; use Object::Method;
This effectively exports a method method to your class, which can be used to create new methods like this:
method
my $o = Stuff->new; $o->method("foo" => sub { ... });
The method method takes exactly two arguments: the method name, and a sub-routine or code-ref. After calling that method method on object $o, a new method foo will be attached to $o and can be invoked only on $o.
$o
foo
The second way is to use it on all objects through UNIVERSAL::Object::Method like this:
UNIVERSAL::Object::Method
use UNIVERSAL::Object::Method; use SomeClass; my $o = SomeClass->new; $o->method("foo" => sub { ... });
This is an overwhelming way due to the use of UNIVERSAL namespace. If you are not familiar with it, read the linked documentation.
The third way is to use it on a class that does not itself use this module at all by using method as a function instead of as a method.
ues Object::Method; use SomeClass; my $o = SomeClass->new; method($o, "foo" => sub { ... });
Please notice that calling the method method multiple times obviously override previous definition and there is no way to undo this for now.
To implement such mechanism, the object on which the method method is invoked are re-blessed into its' own, dynamically created, namespace. You may exam them with ref:
ref
my $x = My::Awesome::Class->new; $x->method("kiss", sub { say ... }); say ref($x); # => My::Awesome::Class#<1> say "$x"; # => My::Awesome::Class#<1>=HASH(0x100826a30)
Those dynamically created classes are properly setup to be inherited from the original classes with @ISA variable. That effects the return value of ref but not isa.
@ISA
isa
The number in the last part of the namespace is a serial that gets incremented when a new object is encountered. If numerous objects are encountered it might consume a very big part of symble table. The mechanism to reap unused classnames are not implemented at this moment.
Kang-min Liu
This is free software, licensed under:
The MIT (X11) License
To install Object::Method, copy and paste the appropriate command in to your terminal.
cpanm
cpanm Object::Method
CPAN shell
perl -MCPAN -e shell install Object::Method
For more information on module installation, please visit the detailed CPAN module installation guide.