3

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.

0

1 Answer 1

12

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

Sign up to request clarification or add additional context in comments.

2 Comments

+1 for Moose. Coming from a similar OO background, all I can say is I don't see why you wouldn't use Moose.
This will break as soon as you start deriving from class X or Y. You should say my $class = shift; my $self = bless {}, $class; there in the constructors.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.