If you just want to attach functionality to a specific object and do not need inheritance, you can save the ref code in the object and call it.
The problem is that you need to check that $obj->{__actions}{something} contains a link to the code. I would suggest including a method around this procedure.
sub add_action { my($self, $action, $code) = @_; $self->{__actions}{$action} = $code; return; } sub take_action { my($self, $action, $args) = @_; my $code = $self->{__actions}{$action}; return if !$code or ref $code ne 'CODE'; return $code->(@$args); } $obj->add_action( "something", sub { ... } ); $obj->take_action( "something", \@args );
If you already know the name of the class into which you want to enter the method, write the routine as usual, but use the full name.
sub Some::Class::new_method { my $self = shift; ... }
Note that any global variables inside this routine will be in the surrounding package, not in Some :: Class. If you want constant variables to use state inside the routine or my outside the routine.
If you do not know the name at compile time, you will need to enter the subroutine in the symbol table so that you are close to the last.
sub inject_method { my($object, $method_name, $code_ref) = @_;
Methods in Perl are associated with a class, not an object. To assign a method to a single object, you must put this object in your class. As above, but you need to create a subclass for each instance.
my $instance_class = "_SPECIAL_INSTANCE_CLASS_"; my $instance_class_increment = "AAAAAAAAAAAAAAAAAA"; sub inject_method_into_instance { my($object, $method_name, $code_ref) = @_;
I left the code to check if this instance does not have this method, checking if its class matches /^${instance_class}::/ . I leave this as an exercise for you. Creating a new class for each object is not cheap and will cost memory.
There are good reasons for this, but they are exceptional. You really have to really wonder if you should do this monkey correction . Generally, distance action should be avoided.
Can you accomplish the same thing using a subclass, delegation, or role?
Perl OO systems already exist that will do this for you and more. You must use it. Moose , Moo (via Role :: Tiny ), and Mouse can add roles to the instance.