cha*_*mmu 5 oop perl inheritance reference
我有一种情况,在子类中,我需要父类中定义的子例程的引用,我需要将其传递给将执行它们的其他类。所以我写了以下示例模块来测试相同的模块。
package Parent1;
sub new {
my ($class, $arg_hash) = @_;
my $self = bless $arg_hash, $class;
return $self;
}
sub printHello{
print "Hello\n";
}
sub printNasty{
print "Nasty\n";
}
1;
Run Code Online (Sandbox Code Playgroud)
package Child1;
use base Parent1;
sub new {
my ($class, $arg_hash) = @_;
my $self = bless $arg_hash, $class;
return $self;
}
sub testFunctionReferences{
my ($self) = @_;
# Case 1: Below 2 lines of code doesn't work and produces error message "Not a CODE reference at Child1.pm line 18."
#my $parent_hello_reference = \&$self->SUPER::printHello;
#&$parent_hello_reference();
# Case 2: Out of below 2 lines of code, 1st line executes the function and produces output of "Hello\n" but 2nd line doesn't work and produces error message "Not a CODE reference at Child1.pm line 23."
#my $parent_hello_reference2 = \$self->SUPER::printHello;
#&$parent_hello_reference2();
# Case 3: does not work either. Says "Undefined subroutine &Child1::printNasty called at Child1.pm line 27"
#my $parent_nasty_reference = \&printNasty;
#&$parent_nasty_reference();
# Case 4: works. prints "World\n" as expected
#my $my_own_function_reference = \&printWorld;
#&$my_own_function_reference();
# Case 5: works. prints "Hello\n" and "Nasty\n" as expected
#$self->printHello();
#$self->SUPER::printNasty();
# Case 6: does not work produces error "Undefined subroutine &Child1::printHello called at Child1.pm line 38"
#printHello();
return;
}
sub printWorld{
print "World\n";
}
Run Code Online (Sandbox Code Playgroud)
#!/usr/bin/perl
use Child1;
my $child = Child1->new({});
$child->testFunctionReferences();
Run Code Online (Sandbox Code Playgroud)
所以我的问题是:
与情况 1 一样,获取对父子例程的引用的正确语法是什么?
当我使用继承时,如何像案例6那样直接调用父函数?在perl中甚至可能吗?
当案例 5 有效时,为什么案例 6 无效?
任何见解表示赞赏。谢谢
如果printHello是子程序,则使用
my $sub = \&Parent::printHello;
Run Code Online (Sandbox Code Playgroud)
如果printHello是一种方法,请使用
# This line must appear inside of the Child package.
my $sub = sub { $self->SUPER::method(@_) };
Run Code Online (Sandbox Code Playgroud)
如果您想要代码引用,则需要一个子例程来引用,这将创建一个子例程。
在这两种情况下,您都可以使用以下命令调用子程序
&$sub();
Run Code Online (Sandbox Code Playgroud)
或者
$sub->();
Run Code Online (Sandbox Code Playgroud)
(我发现后者更干净,但它们在其他方面是等效的。)