gpt4 book ai didi

perl - 我可以使用 MooseX::Declare 在类之外定义函数吗?

转载 作者:行者123 更新时间:2023-12-04 08:01:20 25 4
gpt4 key购买 nike

我最近开始使用模块 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 );
}

我可以看到有一种方法可以使类可变。有谁知道该怎么做?

最佳答案

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

class BankAccount is mutable {
}

顺便说一句,你为什么要在类之外定义你的方法?

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

关于perl - 我可以使用 MooseX::Declare 在类之外定义函数吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/502463/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com