Learning Perl Objects, References amp;amp; Modules [Electronic resources] نسخه متنی

اینجــــا یک کتابخانه دیجیتالی است

با بیش از 100000 منبع الکترونیکی رایگان به زبان فارسی ، عربی و انگلیسی

Learning Perl Objects, References amp;amp; Modules [Electronic resources] - نسخه متنی

Randal L. Schwartz

| نمايش فراداده ، افزودن یک نقد و بررسی
افزودن به کتابخانه شخصی
ارسال به دوستان
جستجو در متن کتاب
بیشتر
تنظیمات قلم

فونت

اندازه قلم

+ - پیش فرض

حالت نمایش

روز نیمروز شب
جستجو در لغت نامه
بیشتر
لیست موضوعات
توضیحات
افزودن یادداشت جدید














9.7 Adding Parameters to a Method


Let's train your
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. Do not rush to
freeze an API design before you've considered how
the object will be used.



/ 199