19、在20分钟内,通过命令行运行module - starter,使用Module::Starter创建你自己的Animal发行版。构建该发行版并运行测试。由于你未做任何更改,所有测试都应通过。为了查看模块中出现错误时会发生什么,在Animal.pm中制造某种语法错误,重新运行测试。此时测试应该失败。不用担心会弄乱任何东西,因为你可以重新运行module - starter!
操作步骤
- 先运行
module-starter创建Animal发行版。 - 接着构建发行版并运行测试,确保测试通过。
- 之后在
Animal.pm中制造语法错误。 - 再次运行测试,此时测试应失败。
- 若弄乱了可重新运行
module-starter。
20、用你的姓名和电子邮件地址设置Module::Starter配置文件,然后重做练习(假设练习是创建包含Animal及相关子类的发行版),替换Animal发行版。
- 先设置Module::Starter配置文件,填入姓名和邮箱地址。
- 若已有Animal发行版,可使用命令
module-starter --module=Cow,Horse,Sheep --dist=.添加模块; - 若没有,则使用命令
module-starter --module=Animal,Cow,Horse,Sheep创建新发行版。
21、在20分钟内,下载并安装Module::Starter::AddModule,将该插件添加到Module::Starter配置文件中,并将Cow模块添加到你的发行版中。
安装 Module::Starter::AddModule 可使用以下命令:
% cpan -I Module::Starter::AddModule
更新配置文件 .module-starter/config 以使用新安装的插件,示例配置如下:
author: Willie Gilligan
email: gilligan@island.example.com
builder: Module::Build
verbose: 1
plugins: Module::Starter::AddModule
若在发行版目录中,使用以下命令添加 Cow 模块:
% module-starter --module=Cow --dist=.
22、创建 Animal、Cow、Horse、Sheep 和 Mouse 类。运行发行版的测试目标,以确保它们都能正确编译(即 t/00 - load.t 测试通过)。根据需要进行修改以使测试通过。
可按以下步骤操作:
- 首先创建
Animal、Cow、Horse、Sheep和Mouse类; - 接着运行发行版的测试目标,保证
t/00-load.t测试通过; - 若测试不通过,对代码进行修改直至测试通过。
同时需注意 t/animal.t 测试,由于 Animal 是角色无法创建新对象,暂时可去掉该测试文件。
23、创建一个程序,要求用户输入一种或多种谷仓动物的名称。用这些动物创建一个谷仓,并让每只动物叫一声。
以下是满足需求的程序代码:
use Cow;
use Horse;
use Mouse;
use Sheep;
my @barnyard = ();
{
print "enter an animal (empty to finish): ";
chomp(my $animal = <STDIN>);
$animal = ucfirst lc $animal; # canonicalize
last unless $animal =~ /^(Cow|Horse|Sheep|Mouse)$/;
push @barnyard, $animal;
redo;
}
foreach my $beast (@barnyard) {
$beast->speak;
}
此代码使用简单的模式匹配检查,确保用户不会输入羊驼或其他不可用的动物,因为这样做会使程序崩溃。
运行程序示例如下:
% perl scripts/barnyard.pl
enter an animal (empty to finish): Cow
enter an animal (empty to finish): Cow
enter an animal (empty to finish): Sheep
enter an animal (empty to finish): Horse
enter an animal (empty to finish): Kangaroo
A Cow goes mooo!
A Cow goes mooo!
A Sheep goes baaaah!
A Horse goes neigh!
最后输入的动物“Kangaroo”会跳出循环,不会进入 @barnyard 数组,所以不会听到它叫。

最低0.47元/天 解锁文章
1351

被折叠的 条评论
为什么被折叠?



