p5-mop-redux
p5-mop-redux copied to clipboard
Can't new object for my class from within a package
If I try to new an object from a mop class from inside a package I get a "Can't locate object method" error. I don't think I am doing anything wrong, here is a very trivial example:
iscah% more *
::::::::::::::
Foo.pm
::::::::::::::
use mop;
class Foo {
}
1;
::::::::::::::
foo.pl
::::::::::::::
package Bar;
use Foo;
my $foo = Foo->new;
iscah% perl foo.pl
Can't locate object method "new" via package "Foo" (perhaps you forgot to load "Foo"?) at foo.pl line 3.
if I remove the package deceleration from foo.pl or if I move the use Foo above the package declaration then it works.
This is not really a bug. When you don't include a package name in your module files, the package they use is "whatever the current package is at the place where the use
statement occurs". In your case, your code is compiling the class Foo
declaration within the Bar
package, and the mop treats that as trying to declare the class Bar::Foo
. The same thing would happen if you did this:
# Foo.pm
sub foo { }
# Bar.pm
package Bar;
use Foo;
# foo.pl
use Bar;
foo();
because the foo
sub will be installed into the Bar
package instead of into main
.
In general, the recommendation of never writing a .pm
file without a package
statement still holds, even with the mop.
Ah thanks, I was able to get it to work by adding a package main
at the top of Foo.pm.
I think an example of the recommended way to construct a .pm
file would be helpful. I didn't see any examples that used packages when I was browsing the documentation. I was able to port one of my projects to mop as an exercise after reading mop::manual::tutorials::moose_to_mop
and it went very smoothly aside from this minor misunderstanding.
@plicease - lets leave this issue open and I will remember to add this to the docs. Thanks!