下面的程序把类型为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
。