我编写了以下模块,但不确定如何引用“last”和“head”节点。以及将下一个节点的地址存储在前一个节点的“{nextNode}”中。
我试图在存储类时保存它的引用,但后来它提示:“不是 List.pm 的 HASH 引用”;我明白为什么,但不确定语法会如何。
如果我取消引用 $head 和 $last ($$last->{nextNode} =\$class) 那么我认为它使用的是我的类(class)的实际名称;列出而不是像我想要的以前的对象。
package List;
my $head = undef;
my $last = undef;
sub new {
my $class = shift;
# init the head of the list
if ($head == undef) {
$head = \$class;
print "updated head to:$head", "\n";
}
$last = \$class;
$last->{nextNode} = \$class; # update previous node to point on this new one
print "updated last to:$last", "\n";
my $self = {};
$self->{value} = shift;
$self->{nextNode} = ""; # reset next to nothing since this node is last
return bless $self, $class;
}
多谢你们
最佳答案
您应该存储 $self
无处不在,而不是 \$class
.存储 $class 只是存储类的名称,而不是对象本身。
此外,对于 $self->{nextNode}
我会存储一个 undef
而不是一个空白字符串。或者更好的是,根本不创建它并使用 exists
检查它是否存在时。
关于perl - 在 Perl 中实现一个节点列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13087892/