kumar
kumar

Reputation: 2796

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

foreach $object (@object_arr) {
  $object->xyz();
}

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

Upvotes: 3

Views: 3905

Answers (1)

Quentin
Quentin

Reputation: 943564

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

Upvotes: 12

Related Questions