如何在 Perl 中用子函数覆盖父类函数?
我想替换子类中的父函数(Somefunc),所以当我调用 Main 过程时它应该失败。
在 Perl 中可以吗?
代码:
package Test;
use strict;
use warnings;
sub Main()
{
SomeFunc() or die "Somefunc returned 0";
}
sub SomeFunc()
{
return 1;
}
package Test2;
use strict;
use warnings;
our @ISA = ("Test");
sub SomeFunc()
{
return 0;
}
package main;
Test2->Main();
I would like to replace parent function (Somefunc) in child class, so when I call Main procedure it should fail.
Is it possible in Perl?
Code:
package Test;
use strict;
use warnings;
sub Main()
{
SomeFunc() or die "Somefunc returned 0";
}
sub SomeFunc()
{
return 1;
}
package Test2;
use strict;
use warnings;
our @ISA = ("Test");
sub SomeFunc()
{
return 0;
}
package main;
Test2->Main();
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
当您调用
Test2->Main()
时,包名称将作为第一个参数传递给被调用函数。您可以使用参数来寻址正确的函数。在此示例中,
$class
将是"Test2"
,因此您将调用Test2->SomeFunc()
。更好的解决方案是使用实例(即bless
Test::new 中的对象,使用$self
而不是$类)。更好的是使用
Moose
,它解决了 Perl 中面向对象编程的很多问题。When you call
Test2->Main()
, the package name is passed as the first parameter to the called function. You can use the parameter to address the right function.In this example,
$class
will be"Test2"
, so you will callTest2->SomeFunc()
. Even better solution would be to use instances (i.e.,bless
the object inTest::new
, use$self
instead of$class
). And even better would be to useMoose
, which solves a lot of problems with object-oriented programming in Perl.为了使继承起作用,您需要使用
->
运算符在类或对象上将函数作为方法调用。您似乎已经为Test2->Main()
的调用弄清楚了这一点,但是您想要以 OO 方式运行的所有方法都必须以这种方式调用。请参阅 perlboot 以获得简单的介绍和 perltoot 了解更多详细信息。
另外,当你声明子例程名称时,不要在它们后面加上括号——它不会按照你的想法做。
In order for inheritance to work you need to call your functions as methods, either on a class or an object, by using the
->
operator. You seem to have figured this out for your call toTest2->Main()
, but all methods that you want to behave in an OO way must be called this way.See perlboot for a gentle introduction and perltoot for more details.
Also, don't put parens after your subroutine names when you declare them -- it doesn't do what you think.