我的Dancer应用程序模块中有以下代码:

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浏览器访问它时,出现以下错误:无法找到对象方法“new ”通过软件包“Dice”(也许您忘记加载“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();
    }
}

最佳答案

我要说的是您忘记了package Dice中的Dice.pm,但是在阅读了Moops之后,我对 namespace 感到困惑。

让我们看看documentation for Moops



如果class DiceDice.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;

关于perl - 我可以在Dancer中实例化一个对象以返回要显示的值吗?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/20526354/

10-09 20:39