访问';自我';当还提交其他参数时,在对象内(perl)
我在试图访问对象内部的访问';自我';当还提交其他参数时,在对象内(perl),perl,oop,Perl,Oop,我在试图访问对象内部的$self和子中的其他变量时收到错误消息。当从对象外部调用子时,一切正常。但是当我试图在对象中访问它时,我得到了一个错误(见下文) 下面是描述我的问题的示例代码: package input; use warnings; use strict; sub new { my $class = shift; my $self = { }; $self->{_name} = shift; bless ($self, $class);
$self
和子
中的其他变量时收到错误消息。当从对象外部调用子
时,一切正常。但是当我试图在对象中访问它时,我得到了一个错误(见下文)
下面是描述我的问题的示例代码:
package input;
use warnings;
use strict;
sub new {
my $class = shift;
my $self = { };
$self->{_name} = shift;
bless ($self, $class);
return $self;
}
sub test1{
my $self = shift;
my $person = shift;
return $self->{_name}." and ".$person;
}
sub test2{
my $self = shift;
my $person = shift;
print test1($self,$person);
}
package Main;
use warnings;
use strict;
my $i = input->new("Jon");
print $i->test1("Me")."\n";
$i->test2();
调用print$i->test1(“Me”)。“\n”代码>工作正常
我喜欢在对象内部的不同函数中访问test1()
。
但是对于$i->test2()代码>我得到了错误
在第22行的串联(.)或字符串中使用未初始化的值$person
如果我愿意写信
sub test2{
my $self = shift;
my $person = "Jim";
print test1($self,$person);
}
这也行
但是,除了$self
之外,我想显式地将一些其他变量传递给sub
。因为我想使用$self
和其他变量。我认为这与是否将$self
传递到子文件
有关,但如果没有我的$self=shift,我无法理解如何访问$self
代码>命令
在第22行的串联(.)或字符串中使用未初始化的值$person
调用test2
方法时,您忘记了$person
参数,即
$i->test2();
应该是
$i->test2("Someone");
my($self,$person)=@
是从中获取值的更现代的方法。(如果没有参数,则删除的第一个值并返回它)在较新版本的Perl上也应该更快。我花了一些时间来理解这些列表及其在Perl中的可能性。