2014-03-02 44 views
1

Moose是否有辦法獲得類方法屬性。我從我以前的問題中學到,像Sub :: Talisman這樣的獨立模塊可以獲得模塊屬性。Perl Moose方法屬性

如果我運行下面的代碼,我得到錯誤「無效的代碼屬性:公衆...」

#============================ 
package BaseClass; 
use Moose; 

#============================ 
package SubClass; 
use Moose; 
extends qw(BaseClass); 

sub greet : Public { 
    my $self = shift; 
    printf("Hello world."); 
} 
#============================ 
package main; 

my $object = SubClass->new(); 

# I need to get the Public attribute of the sub greet in the SubClass package. 
# if the sub has a Public attribute, call it, otherwise, die. 
# does Moose have some methods to get the attributes, I know some other modules like 
# Sub::Talisman can get the sub's attributes. 
$object->greet(); 
#============================ 

我需要得到子的公共屬性在子類中封裝迎接。 如果sub有一個Public屬性,我會做點什麼,否則就是別的。

是否駝鹿有一些方法來獲得屬性,我知道一些其他模塊,如 Sub :: Talisman可以獲得子的屬性。

+0

您可能會發現[此食譜條目](https://metacpan.org/pod/distribution/Moose/lib/Moose/Cookbook/Meta/PrivateOrPublic_MethodMetaclass.pod)有趣。它顯示瞭如何在Moose中實現公共/私有方法,但不添加任何漂亮的語法,如屬性。 – amon

+0

我需要自己獲取屬性,並決定它是否爲Public,因爲我將它標記爲將其運行給可能是Web瀏覽器的調用方。 – daliaessam

+1

在CPAN上的絕大多數方法隱私實現(包括Moose cookbook條目)都只是「如果調用者ne ...'死亡的優化版本。就我而言,這顯示了對真實方法隱私的目的和好處的誤解。如果你想在Perl中使用真正的私有方法,請將一個coderef粘貼到一個詞法變量中。如果你想要私有屬性,請查看[Lexical :: Accessor](https://metacpan.org/pod/Lexical::Accessor)。 – tobyink

回答

2

這裏有MooseX::MethodAttributes它將屬性自省的東西集成到Moose元對象協議中。

但是,您所得到的特定錯誤將不會被解決。要消除該錯誤,您需要定義一個名爲:Public的屬性,以便Perl知道該屬性存在。 Sub::TalismanAttribute::Handlers是可以用來定義屬性的模塊。

+0

以及如何定義屬性:公開以及如何閱讀它,這是我的問題。 – daliaessam

+0

MooseX :: MethodAttributes是一個很好的解決方案,因爲我已經在使用Moose。它就像使用'my $ attr = MyApp-> meta-> get_method('Log') - >屬性一樣簡單; #[「Bar」,「Baz('corge')」]'。 – daliaessam