如果您想添加要使用的模块,请尝试Moose。它提供了您在现代编程环境中所需的几乎所有功能,等等。它进行类型检查、出色的继承、具有自省功能,并使用MooseX::Declare,这是 Perl 类最好的接口之一。看一看:
use MooseX::Declare;
class BankAccount {
has 'balance' => ( isa => 'Num', is => 'rw', default => 0 );
method deposit (Num $amount) {
$self->balance( $self->balance + $amount );
}
method withdraw (Num $amount) {
my $current_balance = $self->balance();
( $current_balance >= $amount )
|| confess "Account overdrawn";
$self->balance( $current_balance - $amount );
}
}
class CheckingAccount extends BankAccount {
has 'overdraft_account' => ( isa => 'BankAccount', is => 'rw' );
before withdraw (Num $amount) {
my $overdraft_amount = $amount - $self->balance();
if ( $self->overdraft_account && $overdraft_amount > 0 ) {
$self->overdraft_account->withdraw($overdraft_amount);
$self->deposit($overdraft_amount);
}
}
}
我自己觉得挺好看的 :) 它是 Perl 对象系统之上的一个层,所以它适用于你已经拥有的东西(基本上。)
使用 Moose,您可以非常轻松地创建子类型,因此您可以确保您的输入是有效的。懒惰的程序员同意:在 Moose 中使子类型工作要做的事情很少,做起来比不做要容易!(来自食谱 4)
subtype 'USState'
=> as Str
=> where {
( exists $STATES->{code2state}{ uc($_) }
|| exists $STATES->{state2code}{ uc($_) } );
};
而 Tada,USState 现在是您可以使用的类型!无需大惊小怪,只需少量代码。如果它不正确,它会抛出一个错误,你类的所有消费者所要做的就是传递一个带有该字符串的标量。如果没问题(应该是……对吗?:))他们像往常一样使用它,并且您的班级免受垃圾的侵害。这多好啊!
Moose 有很多像这样很棒的东西。
相信我。看看这个。:)