在Perl中实现树 - 儿童被切断

Joa*_*him 0 tree perl data-structures

我将在周末学习Perl的面试.为了更深入地理解我正在尝试实现树类.

#use strict;
#use warnings;

package Tree;

sub new {
    my $class   = shift @_;
    my $content = shift @_;
    my @array   = shift @_;
    return bless { "content" => $content, "array" => @array }, $class;
}

sub num_children {
    my $self = shift @_;
    my @array = $self->{"array"};
    return scalar @array;
}

return 1;
Run Code Online (Sandbox Code Playgroud)

为了测试(错误的)树类,我实现了以下测试脚本.

#!/usr/bin/perl

require Tree;

my $t = Tree->new("#", undef);
my $tt = Tree->new("*", undef);
my $tttt = Tree->new("-", undef);
my $ttttt = Tree->new(".", undef);

my @list = ();
push @list, $tt;
push @list, $t;
push @list, $tttt;
push @list, $ttttt;


my $ttt = Tree->new("+", @list);

print $ttt->num_children();
Run Code Online (Sandbox Code Playgroud)

不幸的是,输出1不是我的预期4.我假设数组以某种方式被切断或不自觉地转换为标量.有任何想法吗?

Bor*_*din 5

主要问题是您无法将数组作为单个值传递 - 您必须传递引用.

此外,你永远不应该评论use strictuse warnings.它们是有价值的调试工具,如果您在启用它们时收到错误消息,则应该修复它们正在标记的错误.

这是一个工作 Tree.pm

use strict;
use warnings;

package Tree;

sub new {
    my $class = shift;
    my ($content, $array) = @_;
    return bless { content => $content, array => $array }, $class;
}

sub num_children {
    my $self = shift;
    my $array = $self->{array};
    return scalar @$array;
}

1;
Run Code Online (Sandbox Code Playgroud)

和调用程序tree_test.pl.请注意,您应该use而不是require模块.

#!/usr/bin/perl

use strict;
use warnings;

use Tree;

my @list = map { Tree->new($_) } ('#', '*', '-', '.');

my $ttt = Tree->new('+', \@list);

print $ttt->num_children, "\n";
Run Code Online (Sandbox Code Playgroud)

产量

4
Run Code Online (Sandbox Code Playgroud)