7stud has asked for the wisdom of the Perl Monks concerning the following question:

Dear Monks,

I am getting this error message:

Can't locate object method "display_output" via package "MyClass" at MyClass.pm line 25.

Here is the MyClass constructor:

package MyClass; use strict; use warnings; use 5.010; sub new { my $self = {}; $self->{ObjA_ref} = shift; $self->{ObjB_ref} = shift; bless $self; return $self; }

I pass an ObjA reference and an ObjB reference to that new() function when I create an object of MyClass, e.g.

my $a_ref = ClassA->new(); my $b_ref = ClassB->new(); my $obj_ref = MyClass->new($a_ref, $b_ref);
The line giving me the error is this one:

sub do_stuff { #this function is defined in MyClass $self = shift; $self->{ObjA_ref}->display_output("blah");

The sub display_output() is defined in ClassA.pm. What do I need to add to MyClass.pm to make that work? All files are in the current directory.

Replies are listed 'Best First'.
Re: classes that use composition
by BrowserUk (Patriarch) on Mar 18, 2010 at 11:13 UTC

    Your MyClass constructor is all wrong:

    sub new { my $self = {}; $self->{ObjA_ref} = shift; ## This is the class name Eg. 'MyClass' $self->{ObjB_ref} = shift; ## This is the ClassA ref bless $self; return $self; }

    Try something like this:

    sub new { my $class = shift; ##NB my $self = {}; $self->{ObjA_ref} = shift; $self->{ObjB_ref} = shift; bless $self, $class; return $self; }

    Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
    "Science is about questioning the status quo. Questioning authority".
    In the absence of evidence, opinion is indistinguishable from prejudice.
Re: classes that use composition
by Corion (Patriarch) on Mar 18, 2010 at 10:38 UTC

    If the error message really comes from the line you've shown, then $self->{ObjA_ref} is an instance of MyClass and not of ClassA. So your error lies somewhere else, or you haven't shown us the real code. Data::Dumper on $self can be helpful here.

    It helps us to help you better if you show self-contained code that exhibits the problem and is directly runnable by us, so we can easily replicate your problem.

Re: classes that use composition
by 7stud (Deacon) on Mar 18, 2010 at 11:27 UTC
    Thanks BrowserUK.
      Hi. You probably already know this, but replying to your own original posting is great if you're thanking multiple users, but if you're thanking one specific user, you might as well target him specifically (:
      1. /msg BrowserUk thanks for [id://829387]
      2. Visit Re: classes that use composition and click the "Comment on" link and write your reply
      3. Visit classes that use composition and click the "[reply]" link alongside BrowserUks post and write your reply.

      :D

    A reply falls below the community's threshold of quality. You may see it by logging in.