Operator overloading



examples/perloop/person08/script/person.pl
use strict;
use warnings;
use v5.10;

use Person;
use GrownUp;

my $kid   = Person->new( fname => 'Foo', lname => 'Bar' );
say "Hello $kid";      # Hello Person=HASH(0x8c54d0)

my $parent = GrownUp->new( fname => 'Foo', lname => 'Bar' );
say "Hello $parent";   # Hello Foo Bar

examples/perloop/person08/lib/Person.pm
package Person;
use strict;
use warnings;

sub new {
    my ($class, %args) = @_;

    my $self = \%args;

    bless $self, $class;

    return $self;
}

sub fname {
    my ($self, $value) = @_;

    return $self->{fname};
}

sub lname {
    my ($self, $value) = @_;

    return $self->{lname};
}


1;

examples/perloop/person08/lib/GrownUp.pm
package GrownUp;
use strict;
use warnings;

use parent 'Person';

use overload
    '""' => \&stringify;

sub stringify {
    my ($self) = @_;
    return $self->fname . ' ' . $self->lname;
}


1;