开发者

In Perl, how do I ensure that a sub is invoked as a method from methods of the same object?

I have a class that has a new method and uses that object to call method X. When I call X from the object the first value of the parameters is $self and the rest are the values I sent in. Now when I call that same method from another method on the object the first value is no longer $self and its just the values being sent in. How do I address this situation?

Sample:

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

but i开发者_如何学JAVAf in 'mymethod' is called by another method:

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

How do I write 'mymethod' so it handle both situations? Or am I fundamentally doing something incorrect?


Just as you did this:

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

you need to be explicit about what object you are calling the method on (even within the class):

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


This is Not A Good Idea (you ought to decide whether a subroutine is a method or not and use it in a consistent way), but in moments of weakness I have used constructions like:

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 stare at this code for a few hours before the shame pools in my gut and I have to fix it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜