Section 12.3. Accessing the Instance Data


12.3. Accessing the Instance Data

Because we get the instance as the first parameter, we can now access the instance-specific data. In this case, let's add a way to get at the name:

 { package Horse;   @ISA = qw(Animal);   sub sound { 'neigh' }   sub name {     my $self = shift;     $$self;   } } 

Now we call for the name:

 print $tv_horse->name, " says ", $tv_horse->sound, "\n"; 

Inside Horse::name, the @_ array contains just $tv_horse, which the shift stores into $self. It's traditional to shift the first parameter into a variable named $self for instance methods, so stay with that unless you have strong reasons to do otherwise (Perl places no significance on the name $self, however).[] Then we dereference $self as a scalar reference, yielding Mr. Ed. The result is:

] If you come from another OO language background, you might choose $this or $me for the variable name, but youll probably confuse most other Perl OO hackers.

 Mr. Ed says neigh. 




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