我已经实现了一个名为cell的类,并尝试将char存储到它。我发现用我的setter和getter检索char有一个问题。
#This is the detail of the class:
package Cell;
sub new{
my $class = shift;
my $self = {
content => -1,
};
return bless $self, $class;
}
#This is my setter and getter
sub setContent{
my ($self,$ch) = @_;
$self->{content} = $ch;
print("stored char".$self->{content}."\n");
}
sub getContent{
my $self = @_;
print("passing back char".$self->{content}."\n");
return $self->{content};
}
# this is the way i used the class
my $ch = "a";
my $cell = Cell->new();
$cell->setContent($ch);
my $testvar = $cell->getContent();
print("test start\n".$testvar);
print("test end\n");
#
我发现我能够将char传递给setter并且应该存储在$ self - > {content}中,但是当尝试使用getter检索char时,$ self - > {content}变为空
一个直接错误是你的“getter”getContent
方法中的一行:
my $self = @_; # assigns number of elements in the array to $self!
这会尝试将一个数组分配给一个标量,这是没有意义的。相反,做的是将数组计算为其元素的数量,并将其分配给$self
。因此在该方法的其余部分中,$self
中没有对象,但只有一个数字,这里是1
。
如果您通过程序顶部的warnings启用use warnings;
,您将收到
不能使用字符串(“1”)作为HASH参考,而“严格参考”在使用时...
对于您尝试在$self
上调用方法的行,告诉您预期的对象(hashref)实际上是一个字符串。这为您提供了精确的线条和信息,如果简洁,diagnostic message。如果没有启用警告,代码将悄然进行,但无法按预期执行。
道德:请在开头时始终有use warnings
(和use strict
)
修复是使其成为“列表分配” - 在列表“上下文”中分配
my ($self) = @_;
列表上下文由=
在左侧强加给赋值运算符(...)
。现在,数组@_
中的元素被分配给()
中列出的变量,一对一。 LHS上只有一个变量($self
)所以@_
的第一个元素被分配给它,其余的,如果有的话,被丢弃。
或者,在标量赋值中将@_
的单个元素赋值给$self
。在面向对象的代码中,这通常使用shift完成,因此也要从参数列表中删除对象以便以后使用
my $self = shift;
默认情况下,子程序中的shift
适用于@_
。