构建大型 Perl 程序的实用指南
1. 代码复用的需求
随着程序规模的不断扩大,我们会发现部分代码可应用于其他任务。此时,将这些代码移至一个库中,就能在多个程序间共享,甚至与他人分享。同时,还能依据功能或用途对代码进行模块化,将其与执行无关任务的代码分离。
1.1 常见代码问题
假设有一位船长,他编写了许多 Perl 程序为船只导航。在这些程序里,他频繁复制粘贴一个通用例程:
sub turn_toward_heading {
my $new_heading = shift;
my $current_heading = current_heading( );
print "Current heading is ", $current_heading, ".\n";
print "Come about to $new_heading ";
my $direction = 'right';
my $turn = ($new_heading − $current_heading) % 360;
if ($turn > 180) { # long way around
$turn = 360 − $turn;
$direction = 'left';
}
print "by turning $direction $turn degrees.\n";
}
这个例程能给出从当前航向转向新航向的最短转向角度。该子程序的第一行也可写成 my ($new_heading) = @_; ,这
超级会员免费看
订阅专栏 解锁全文
11

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



