Moo:将属性添加到另一个(非当前)包

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

以下是我真实代码的简化示例:

#!/usr/bin/perl

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;

X::add_attr_for_another_package('Y');

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

我尝试从包 X 中定义的函数向包 Y 添加属性。这不起作用:

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

请帮助我如何从另一个包中定义的方法向包添加属性。

我应该改用 Moose 吗?

package 影响代码编译到的包。它显然不会影响已经编译的代码(例如对 has 的调用)!换句话说,必须在 package 指令生效时编译对 has 的调用才能受其影响。

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