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

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

相关文章

1. 如何去重 #!/usr/bin/perl use strict; my %hash; while(...
最近写了一个perl脚本,实现的功能是将表格中其中两列的数据...
表的数据字典格式如下:如果手动写MySQL建表语句,确认麻烦,...
巡检类工作经常会出具日报,最近在原有日报的基础上又新增了...
在实际生产环境中,常常需要从后台日志中截取报文,报文的形...
最近写的一个perl程序,通过关键词匹配统计其出现的频率,让...