perlmoose

Accessing Moose object in package to be called explicitly outside


for a Moose package, I am trying to create a object in Perl (non-moose) and then trying to access a method outside. Code to explain this situation is here.

package person;
{
    use Moose;
    sub test {
        print "my test print";
    }
}

package people {
    use person;
    my $obj = person->new();
}

$people::obj->test()

I am getting following Error on executing this perl code.

Can't call method "test" on an undefined value at test.pm 

Am I missing anything here ?


Solution

  • You never assigned anything to $people::obj. You assigned something to an unrelated lexical var named $obj, a variable that doesn't even exist by the time the program reaches the method call. Lexical vars (e.g. those created by my) are scoped to the innermost curlies in which they are located, which is to say they are only visible (accessible) there.

    Fix:

    package Person;
    {
        use Moose;
    
        sub test {
            print "my test print";
        }
    }
    
    package People {
        my $obj = person->new();
    
        sub get_person {
           return $obj;
        }
    }
    
    People->get_person->test();
    

    Notes: