porton porton - 1 year ago 70
Perl Question

Moo: Add attribute to another (non-current) package

The following is a simplified example of my real code:


package X;
use Moo;

sub add_attr_for_another_package {
my ($package) = @_;
eval "package $package";
has 'q' => (is=>'rw', default=>123);

package Y;
use Moo;


my $obj = Y->new;
print $obj->q, "\n";

I try to add an attribute to package
from a function defined in package
. This does not work:

$ ./test.pl
Can't locate object method "q" via package "Y" at ./test.pl line 18.

Please help how can I add an attribute to a package from a method defined in another package.

Should I switch to Moose?

Answer Source

package affects the package into which code is compiled. It obviously won't affect code that's already been compiled (e.g. the call to has)!

sub add_attr_for_another_package {
  my ($package) = @_;
    package $package;
    has 'q' => (is=>'rw', default=>123);
    return 1;
    or die $@;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download