if ( ref($self) eq 'person') { $self->tellName(); }
if ( ref($self) eq 'child') {$self->SUPER::tellName();}
####
Hello, I'm Alice.
Hi, I'm Billy The Kid.
Can't locate object method "tellName" via package "person" at ./classtest line 25.
Here's my mom: Hello, I'm
####
#!/usr/bin/perl
use strict;
package person;
sub new
{
my $class = shift(@_);
my $self = { 'name' => 'Alice' };
bless($self, $class);
return($self);
}
sub tellName {
my($self)=$_[0];
print "$self->{'name'}.\n";
}
sub introduce {
my($self)=$_[0];
print "Hello, I'm ";
# $self->tellName(); # original code
# tellName($self); # one solution offered by perlmonks
#print "\ndebug info: " . ref($self) . "\n";
if ( ref($self) eq 'person'){ $self->tellName(); }
if ( ref($self) eq 'child') { $self->SUPER::tellName();}
}
1;
package child;
our @ISA = qw(person); # inherits from person
sub new {
my $class = shift(@_);
my $self = $class->SUPER::new();
$self ->{'nickName'} = 'Billy The Kid';
bless $self, $class;
return $self;
}
sub tellName {
my($self)=$_[0];
print "$self->{'nickName'}.\n";
}
sub introduce {
my($self)=$_[0]; print "Hi, I'm ";
$self->tellName();
print "Here's my mom: ";
$self->SUPER::introduce();
}
1;
package main;
my $mom = new person();
$mom->introduce(); # that time it works.
print "\n";
my $son = new child();
$son->introduce();