我可以在Dancer中实例化一个对象来返回要显示的值吗?

Bac*_*777 6 perl dancer moo moops

我的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;
Run Code Online (Sandbox Code Playgroud)

我有一个名为Dice.pm的Moops类,如果用.pl文件测试它就可以正常工作,但是当我尝试通过Web浏览器访问它时,我收到以下错误:找不到对象方法"new"通过包"骰子"(也许你忘了加载"骰子"?).

我可以和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();
    }
}
Run Code Online (Sandbox Code Playgroud)

sim*_*que 3

我本来想说你忘记了package Dice中的Dice.pm,但是在阅读了 Moops 后我对命名空间感到困惑。

让我们看一下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
Run Code Online (Sandbox Code Playgroud)

如果它class Dice在里面,如果我正确阅读的话,Dice.pm它实际上会变成。Dice::Dice所以你必须用use Dice来创建你的对象Dice::Dice->new

为了使用 Moops 制作包DiceDice.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();
    }
}
Run Code Online (Sandbox Code Playgroud)

然后你可以这样做:

use Dice;
Dice->new;
Run Code Online (Sandbox Code Playgroud)