2013-12-11 70 views
6

我有我的舞者應用模塊下面的代碼:我可以在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類,如果我有一個特等文件來測試它的作品就好了,但是當我嘗試訪問它通過網絡瀏覽器,我得到以下錯誤:無法通過軟件包「Dice」找到對象方法「new」(也許你忘了加載「Dice」?)

我可以和舞者一起做這個嗎?

這裏是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

我想你'使用骰子;'? – ThisSuitIsBlackNot

+0

@ThisSuitIsBlackNot錯誤消息表明他們*不*具有'使用骰子;' –

+0

使用骰子確實在腳本的頂部。我更新了代碼以顯示整個腳本。 – BackPacker777

回答

3

我要說你在Dice.pm忘了package Dice,但Moops讀了之後我感到困惑的命名空間。

我們來看看documentation for Moops

If you use Moops within a package other than main, then package names used within the declaration are "qualified" by that outer package, unless they contain "::". So for example:

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 DiceDice.pm它實際上將成爲Dice::Dice如果我讀這正確。所以你必須use Dice並用Dice::Dice->new創建你的對象。

爲了讓使用Moops Dice.pm內包Dice,我相信你需要聲明類是這樣的:

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; 
+0

我必須說這個行爲有點奇怪。 – simbabque

+0

我實施了你的建議,但可惜我得到了同樣的錯誤。感謝您的詳細回覆! – BackPacker777

+0

我改變了你的實現,它的工作原理!我用雙冒號聲明類,但是像這樣實例化:Dice-> new – BackPacker777

相關問題