可以通过模块之间的Perl对象引用吗? [英] Can one pass Perl object references between modules?
本文介绍了可以通过模块之间的Perl对象引用吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
示例代码:
package testClass1;
{
my $testClass2Ref;
sub new
{
my($class) = shift;
$testClass2Ref= shift;
bless $self, $class;
return $self;}
}
sub testRef
{
$testClass2Ref->testRef;
}
}
testClass2.pm
testClass2.pm
package testClass2;
{
sub new
{
my($class) = shift;
bless $self, $class;
return $self;}
}
sub testRef
{
print "Test 2";
}
}
test.pl
test.pl
use testClass1;
use testClass2;
my $testClass2 = testClass2->new();
my $testClass1 = testClass2->new($testClass2);
$testClass1->testRef;
当我尝试调用 $ testClass1-> testRef $ c $
When I try call $testClass1->testRef
, $testClass2Ref=undef
.
如何从父对象传递对象的引用?
How can I pass reference on the object from parent?
哦,对不起,我错过了在例子的构造函数中的字符串。
Oh, sorry, I missed string in example's constructors.
sub new
{
my($class) = shift;
$testClass2Ref = shift;
my $self = {name=>'testClass1'};
bless $self, $class;
return $self;
}
这个测试是可行的,但Eclipse调试器显示这个变量为'undef'。
This test is working, but Eclipse debugger show this variables as 'undef'.
感谢您的帮助。
推荐答案
您没有使用 strict
模式。打开它会显示 $ self
没有在任何包中声明。通过替换:
Besides the syntax errors, you aren't using strict
mode. Turning it on will reveal that $self
isn't being declared in either package. By replacing:
bless $self, $class;
其中:
my $self = bless {}, $class;
一切正常。
这篇关于可以通过模块之间的Perl对象引用吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文