加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

如何在Perl对象中定义pre / post-increment行为?

发布时间:2020-12-15 21:13:28 所属栏目:大数据 来源:网络整理
导读: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::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,perltooc和perlbot,但是我没有看到任何可以做到这一点的例子.

解决方法

你要 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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读