Документация
HTML CSS PHP PERL другое

Section 12.7.  Adding Parameters to a Method

 
Previous
Table of Contents
Next

12.7. Adding Parameters to a Method

Let's train our animals to eat:

{ package Animal;
  sub named {
    my $class = shift;
    my $name = shift;
    bless \$name, $class;
  }
  sub name {
    my $either = shift;
    ref $either
      ? $$either # it's an instance, return name
      : "an unnamed $either"; # it's a class, return generic
  }
  sub speak {
    my $either = shift;
    print $either->name, ' goes ', $either->sound, "\n";
  }
  sub eat {
    my $either = shift;
    my $food = shift;
    print $either->name, " eats $food.\n";
  }
}
{ package Horse;
  @ISA = qw(Animal);
  sub sound { 'neigh' }
}
{ package Sheep;
  @ISA = qw(Animal);
  sub sound { 'baaaah' }
}

Now try it out:

my $tv_horse = Horse->named('Mr. Ed');
$tv_horse->eat('hay');
Sheep->eat('grass');

It prints:

Mr. Ed eats hay.
an unnamed Sheep eats grass.

An instance method with parameters gets invoked with the instance, and then the list of parameters. That first invocation is like:

Animal::eat($tv_horse, 'hay');

The instance methods form the Application Programming Interface (API) for an object. Most of the effort involved in designing a good object class goes into the API design, because the API defines how reusable and maintainable the object and its subclasses will be. Don't rush to freeze an API design before you've considered how you (or others) will use the object.


Previous
Table of Contents
Next
© 2000- NIV