perl中的对象数组?

kum*_*mar 3 arrays perl constructor object

我是perl的新手,并且认真地发现很难使用它的面向对象的功能,因为我来自C++,python Background.我想创建一个对象列表,但我不知道如何在perl中实现这一点.我开始使用数组,但这似乎不起作用.

package X;

sub new {
   .....
}


package Y;

sub new {
  .....

}

package Z;

my @object_arr = ( X::new, Y::new);

foreach $object (@object_arr) {
  $object->xyz();
}
Run Code Online (Sandbox Code Playgroud)

这会抛出错误"无法调用方法"xyz"没有包或对象引用".任何帮助表示赞赏.

Que*_*tin 11

带有注释的代码的固定版本是:

package X;

# You need to return a blessed object 
sub new { 
        my $self = bless {}, "X";
        return $self;
}

# You need to define xyz before calling it
sub xyz {
        print "X";
}

package Y;

sub new {
        my $self = bless {}, "Y";
        return $self;

}


sub xyz {
        print "Y";
}

package Z;

# You need to call the new method
my @object_arr = ( X->new(), Y->new());

# Don't forget to my when defining variables (including $object)
foreach my $object (@object_arr) {
  $object->xyz();
}
Run Code Online (Sandbox Code Playgroud)

您可能还想调查Moose

  • 一旦你开始从X或Y级派生,这将会中断.你应该说`my $ class = shift; 我的$ self = bless {},$ class;`在构造函数中. (7认同)