Accessing Moose object in package to be called explicitly outside

Viewed 54

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 ?

2 Answers

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:

  • Removed use person; which either prevented the program from compiling, or unintentionally executed some potentially-conflicting code.
  • Lowercase module names are reserved for pragmas.
  • I could have have changed the lexical variable into a package variable, but using global variable is a bad practice. Using a method (or sub) can make things a lot easier in the future.
  • Be careful putting multiple packages/classes in one file. There are pitfalls.

If you do want to use $obj as a global variable and use it outside the package, you have to define it as such with our. Changing

    my $obj = person->new();

to

    our $obj = person->new();

and your script works. But using globals - even via getters as ikegami proposed - is often a bad idea.

Related