In Perl, how can I guarantee that sub is called as a method from methods of the same object?

I have a class that has a new method and uses this object to call method X. When I call X from the object, the first parameter value is $ self, and the rest are the values ​​that I sent. Now, when I call the same method from another method on an object, the first value is no longer $ self and its just the values ​​sent internally. How can I solve this situation?

Example:

my $p = TEST->new; $p->mymethod(1,2,3); # @_ = 'self, 1, 2, 3' 

but if in 'mymethod' is called by another method:

 sub anothermethod{ my ($self, $a) = @_; mymethod(1,2,3); # @_ = '1,2,3' } 

How to write "mymethod" so that it handles both situations? Or am I fundamentally doing something wrong?

+2
perl
source share
2 answers

How did you do that:

 $p->mymethod(1,2,3); 

you need to explicitly indicate to which object you are calling the method (even inside the class):

 $self->mymethod(1,2,3); 
+9
source share

This is not a good idea (you have to decide whether the subroutine is a method or not and use it in a consistent way), but in moments of weakness I used constructs such as:

 sub subroutine_that_may_get_called_like_a_method { shift if ref $_[0] eq __PACKAGE__; my ($param1, $param2) = @_; ... } sub method_that_may_get_called_like_a_subroutine { unshift @_, __PACKAGE__ if ref $_[0] ne __PACKAGE__ my ($self, $param1, $param2) = @_; ... } 

Usually I can only look at this code a few hours before the shame in my gut is empty and I have to fix it.

+2
source share

All Articles