Section 12.5. Inheriting the Constructor


12.5. Inheriting the Constructor

Was there anything specific to Horse in that method? No. Therefore, it's also the same recipe for building anything else inherited from Animal, so let's put it there:

 { package Animal;   sub speak {     my $class = shift;     print "a $class goes ", $class->sound, "!\n"   }   sub name {     my $self = shift;     $$self;   }   sub named {     my $class = shift;     my $name = shift;     bless \$name, $class;   } } { package Horse;   @ISA = qw(Animal);   sub sound { 'neigh' } } 

Ahh, but what happens if we invoke speak on an instance?

 my $tv_horse = Horse->named('Mr. Ed'); $tv_horse->speak; 

We get a debugging value:

 a Horse=SCALAR(0xaca42ac) goes neigh! 

Why? Because the Animal::speak method expects a class name as its first parameter, not an instance. When we pass in the instance, we'll use a blessed scalar reference as a string, which shows up as we showed it just nowsimilar to a stringified reference, but with the class name in front.




Intermediate Perl
Intermediate Perl
ISBN: 0596102062
EAN: 2147483647
Year: N/A
Pages: 238

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net