overridden method in perltoot

C

cmic

Hi
context : PerlOO Newbie.
I don't understand why this excerpt from perltoot doesn't work as
expected.
It should print "In Employe::peers", but prints "In Person::peers"
instead.
Moreover, the complete example in perltoot ("Overridden method"
paragraph) doesn't work either.
Or do I miss something ?

--------file Person.pm-------------
#!/usr/local/bin/perl
package Person;
use strict; use warnings;
sub new {
my $self = {};
$self->{NAME} = undef;
bless($self);
return $self;
}
sub name {}

sub peers { print "in Person::peers\n";}
1;

--------------file Employe.pm -----------
#!/usr/local/bin/perl
package Employe;
use Person;
use vars qw (@ISA);

use strict; use warnings;
@ISA="Person";

sub peers {
printf "In Employe::peers\n";
}

----------file a.pl -----------
#!/usr/local/bin/perl
use Employe;
use strict;
use warnings;

my $emp=Employe->new();
print $emp->peers(), "\n";


TYA
 
D

Dave Weaver

Hi
context : PerlOO Newbie.
I don't understand why this excerpt from perltoot doesn't work as
expected.
It should print "In Employe::peers", but prints "In Person::peers"
instead.
Moreover, the complete example in perltoot ("Overridden method"
paragraph) doesn't work either.
Or do I miss something ?

It appears that you missed the perltoot section
"Planning for the Future: Better Constructors" where the constructor
is revised.

--------file Person.pm-------------
#!/usr/local/bin/perl
package Person;
use strict; use warnings;
sub new {
my $self = {};
$self->{NAME} = undef;
bless($self);

This blesses $self into the current package (i.e. Person) so, even
when called via the Employee constructor, the result is always a
Person, not an Employee.

You need to bless $self into the correct class (which is usually the
first parameter passed to the constructor):

sub new {
my $class = shift;

# ...

return bless $self, $class;
}

Now, when called via: $x = Person->new()
$x will be a Person, but when called via: $x = Employee->new()
then $x will be an Employee.
 
C

cmic

Hello

....
    bless($self, $class);


See the "Planning for the Future: Better Constructors" section in perltoot,
and note what the single-arg form of bless() does:

    perldoc -f bless

    ... Always use the two-argument version if a derived class might
    inherit the function doing the blessing...

OK. I dig it. (In short, this another form of RTFM :cool: )
Thanks to Tad and Dave.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,969
Messages
2,570,161
Members
46,708
Latest member
SherleneF1

Latest Threads

Top