Implicit Type Conversion in Perl

下面的程序把类型为Person的对象隐式转换为字符串和整数。

#!/usr/bin/perl

package Person;
use overload '0+' => &age, # convert type to integer
   '""' => &name,           # convert type to string
   fallback => 1;            # make ($p - $a) possible

sub new {
   my ($this, $name, $age) = @_;
   my $class = ref($this) || $this;
   my $self = { name => $name, age => $age };
   bless $self, $class;
   return $self;
}

sub name {
   my $self = shift;
   return $self->{name};
}

sub age {
   my $self = shift;
   return $self->{age};
}

package main;

$p = Person->new("Old Brother", 20);
print $p->name, " is ", $p->age, " years old.n";
$a = Person->new("Young Sister", 8);
print $a->name, " is ", $a->age, " years old.n";
print $p, " is ", $p - $a, " year older than ", $a, ".n";

overload的详细信息参见perldoc overload

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据