在Perl中实现一个节点列表

Yan*_*vid 4 perl implementation list

我编写了以下模块但不确定如何引用"last"和"head"节点.以及将下一个节点的地址存储在前一节点的"{nextNode}"中.

我试图在存储它时保存类的引用,但后来它抱怨:"不是List.pm中的HASH引用"; 我明白为什么但不确定语法是怎样的.

如果我取消引用$ head和$ last($$ last - > {nextNode} =\$ 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;
}
Run Code Online (Sandbox Code Playgroud)

多谢你们

Wes*_*ker 6

你应该存储$self到处而不是\$class.存储$ class只是存储类的名称,而不是对象本身.

另外,因为$self->{nextNode}我存储了undef一个空字符串而不是空字符串.或者更好的是,根本不要创建它并exists在检查它是否存在时使用.