我的Dancer app模块中有以下代码:
package Deadlands;
use Dancer ':syntax';
use Dice;
our $VERSION = '0.1';
get '/' => sub {
my ($dieQty, $dieType);
$dieQty = param('dieQty');
$dieType = param('dieType');
if (defined $dieQty && defined $dieType) {
return Dice->new(dieType => $dieType, dieQty => $dieQty)->getStandardResult();
}
template 'index';
};
true;
我有一个名为Dice.pm的Moops类,如果用.pl文件测试它就可以正常工作,但是当我尝试通过Web浏览器访问它时,我收到以下错误:不能通过包“Dice”找到对象方法“new”(也许你忘了加载“Dice”?)。
我可以和Dancer一起做吗?
以下是Dice.pm的相关代码:
use 5.14.3;
use Moops;
class Dice 1.0 {
has dieType => (is => 'rw', isa => Int, required => 1);
has dieQty => (is => 'rw', isa => Int, required => 1);
has finalResult => (is => 'rw', isa => Int, required => 0);
method getStandardResult() {
$self->finalResult(int(rand($self->dieType()) + 1));
return $self->finalResult();
}
}
答案 0 :(得分:3)
我打算说你忘记了package Dice
中的Dice.pm
,但在阅读了Moops后,我对名称空间感到困惑。
让我们来看看documentation for Moops。
如果在main之外的包中使用Moops,则包名称 声明中使用的“外部包裹”是“合格的”, 除非它们包含“::”。例如:
package Quux; use Moops; class Foo { } # declares Quux::Foo class Xyzzy::Foo # declares Xyzzy::Foo extends Foo { } # ... extending Quux::Foo class ::Baz { } # declares Baz
如果class Dice
位于Dice.pm
,如果我正确阅读,它实际上将成为Dice::Dice
。因此,您必须use Dice
并使用Dice::Dice->new
创建对象。
为了使用Moops在Dice
内创建包Dice.pm
,我相信您需要声明这样的类:
class ::Dice 1.0 {
# ^------------- there are two colons here!
has dieType => (is => 'rw', isa => Int, required => 1);
has dieQty => (is => 'rw', isa => Int, required => 1);
has finalResult => (is => 'rw', isa => Int, required => 0);
method getStandardResult() {
$self->finalResult(int(rand($self->dieType()) + 1));
return $self->finalResult();
}
}
然后你可以这样做:
use Dice;
Dice->new;