开发者

Arrays of objects in perl?

I am new to perl and seriously finding it difficult to use its object oriented features as I come from C++,python Background. I wanted to create a list of objects , but I dont know how to achieve this in perl. I started with an array , but that doesn't seem to be working.

package X;

sub new {
   .....
}


package Y;

sub new {
  .....

}

package Z;

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

foreac开发者_运维知识库h $object (@object_arr) {
  $object->xyz();
}

This throws an error "Can't call method "xyz" without a package or object reference ". Any help is appreciated.


A fixed up version of your code, with comments, is:

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();
}

You might also want to investigate Moose

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜