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

前端之家收集整理的这篇文章主要介绍了如何在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.
  1. package Number;
  2.  
  3. use overload
  4. '0+' => \&as_number,'++' => \&incr,;
  5.  
  6. sub new {
  7. my ($class,$num) = @_;
  8.  
  9. return bless \$num => $class;
  10. }
  11.  
  12. sub as_number {
  13. my ($self) = @_;
  14.  
  15. return $$self;
  16. }
  17.  
  18. sub incr {
  19. my ($self) = @_;
  20.  
  21. $_[0] = Number->new($self->as_number + 1); # note the modification of $_[0]
  22. return;
  23. }
  24.  
  25. package main;
  26.  
  27. my $num = Number->new(5);
  28. print $num . "\n"; # 5
  29. print $num++ . "\n"; # 5
  30. print ++$num . "\n"; # 7

猜你在找的Perl相关文章