gpt4 book ai didi

perl - 如何在 Perl 对象中定义前/后增量行为?

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

Date::Simple 对象显示此行为,其中 $date++返回第二天的日期。

Date::Simple objects are immutable. After assigning $date1 to $date2, no change to $date1 can affect $date2. This means, for example, that there is nothing like a set_year operation, and $date++ assigns a new object to $date.



如何自定义对象的前/后增量行为,例如 ++$object$object--执行特定操作?

我浏览过 perlboot , perltoot , perltoocperlbot ,但我没有看到任何示例说明如何做到这一点。

最佳答案

您要 overload .

package Number;

use overload
'0+' => \&as_number,
'++' => \&incr,
;

sub new {
my ($class, $num) = @_;

return bless \$num => $class;
}

sub as_number {
my ($self) = @_;

return $$self;
}

sub incr {
my ($self) = @_;

$_[0] = Number->new($self->as_number + 1); # note the modification of $_[0]
return;
}

package main;

my $num = Number->new(5);
print $num . "\n"; # 5
print $num++ . "\n"; # 5
print ++$num . "\n"; # 7

关于perl - 如何在 Perl 对象中定义前/后增量行为?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2756352/

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