在 Perl 中,如何确保从同一对象的方法中调用子方法?
我有一个类,它有一个新方法,并使用该对象来调用方法 X。当我从该对象调用 X 时,参数的第一个值是 $self,其余的是我发送的值。现在,当我调用相同的方法时方法从对象上的另一个方法中第一个值不再是 $self 并且它只是发送的值。我该如何解决这种情况?
示例:
my $p = TEST->new;
$p->mymethod(1,2,3); # @_ = 'self, 1, 2, 3'
但是如果“mymethod”中被另一个方法调用:
sub anothermethod{
my ($self, $a) = @_;
mymethod(1,2,3); # @_ = '1,2,3'
}
我该如何编写“mymethod”以便它处理这两种情况?或者我根本上做错了什么?
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 if 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
正如您所做的那样:
您需要明确要在哪个对象上调用该方法(即使在类内):
Just as you did this:
you need to be explicit about what object you are calling the method on (even within the class):
这不是一个好主意(你应该决定一个子例程是否是一个方法,并以一致的方式使用它),但在弱点的时刻,我使用了这样的结构:
通常我只能盯着这段代码看一会儿几个小时前,羞耻感就在我的内心积聚起来,我必须解决它。
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:
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.