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

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

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

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

Randal L. Schwartz

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

فونت

اندازه قلم

+ - پیش فرض

حالت نمایش

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














8.1 If We Could Talk to the Animals...


Obviously, the castaways can't survive on coconuts
and pineapples alone. Luckily for them, a barge carrying random farm
animals crashed on the island not long after they arrived, and the
castaways began farming and raising animals.

Let's let those animals talk for a moment:

sub Cow::speak {
print "a Cow goes moooo!\n";
}
sub Horse::speak {
print "a Horse goes neigh!\n";
}
sub Sheep::speak {
print "a Sheep goes baaaah!\n";
}
Cow::speak;
Horse::speak;
Sheep::speak;

This results in:

a Cow goes moooo!
a Horse goes neigh!
a Sheep goes baaaah!

Nothing spectacular here: simple subroutines, albeit from separate
packages, and called using the full package name.
Let's create an entire pasture:

sub Cow::speak {
print "a Cow goes moooo!\n";
}
sub Horse::speak {
print "a Horse goes neigh!\n";
}
sub Sheep::speak {
print "a Sheep goes baaaah!\n";
}
my @pasture = qw(Cow Cow Horse Sheep Sheep);
foreach my $beast (@pasture) {
&{$beast."::speak"}; # Symbolic coderef
}

This results in:

a Cow goes moooo!
a Cow goes moooo!
a Horse goes neigh!
a Sheep goes baaaah!
a Sheep goes baaaah!

Wow. That symbolic coderef dereferencing there in the body of the
loop is pretty nasty. We're counting on
no strict
'refs' mode, certainly not recommended for larger
programs.[1]
And why was that necessary? Because the name of the package seems
inseparable from the name of the subroutine you want to invoke within
that package.

[1] Although all examples in this book should
be valid Perl code, some examples in this chapter will break the
rules enforced by use strict to make them easier
to understand. By the end of the chapter, though,
you'll learn how to make
strict-compliant code again.


Or is it?



/ 199