我可以使用MooseX :: Declare定义类外的函数吗?

时间:2009-02-02 07:42:04

标签: perl module moose

我最近开始使用模块MooseX::Declare。我喜欢它的语法。它优雅而整洁。有没有人遇到过你想要在类中编写许多函数(其中一些很大)和运行到页面中的类定义的情况?是否有任何解决方法使类定义只是声明函数和类外的实际函数定义?

我要找的是这样的 -

class BankAccount {
    has 'balance' => ( isa => 'Num', is => 'rw', default => 0 );
    # Functions Declaration.
    method deposit(Num $amount);
    method withdraw(Num $amount);
}

# Function Definition.
method BankAccount::deposit (Num $amount) {
    $self->balance( $self->balance + $amount );
}

method BankAccount::withdraw (Num $amount) {
    my $current_balance = $self->balance();
    ( $current_balance >= $amount )
    || confess "Account overdrawn";
    $self->balance( $current_balance - $amount );
}

我可以看到有一种方法可以让这个类变得可变。有谁知道怎么做?

2 个答案:

答案 0 :(得分:7)

容易(但需要添加到文档中)。

class BankAccount is mutable {
}

顺便说一下,为什么要在课外定义你的方法?

你可以去

class BankAccount is mutable {
    method foo (Int $bar) {
         # do stuff
    }
}

答案 1 :(得分:0)

我希望我的类定义简短,并给出一个关于类的用途的抽象概念。我喜欢在C ++中完成它的方式,你可以选择使用范围解析运算符在内部或类外定义函数。这使得类定义简洁而整洁。这就是我要找的。

感谢您的时间。