2

您如何决定是将代码放在子程序中还是放在 Perl 脚本的主要部分中?

我知道如果你需要重用代码,你会把它放在子程序中,但是如果你不重用怎么办?将子例程放入对代码进行分组并使其更易于阅读是一种好习惯吗?

示例(主要):

my ($num_one, $num_two) = 1, 2;
print $num_one + $num_two;
print $num_one - $num_two;

示例(在子程序中):

 my ($num_one, $num_two) = 1, 2;
 add($num_one, $num_two);
 subtract($num_one, $num_two);

 sub add {
     my ($num_one, $num_two) = @_;
     return $num_one + $num_two;
 }

 sub subtract {
     my ($num_one, $num_two) = @_;
     return $num_one - $num_two;
 }    

我知道这是一个简单的例子,但是对于更复杂的代码(如果 sub add 和 subsubtract 有更多的代码),分组子程序是否有意义?

谢谢!

4

4 回答 4

4

我想补充一点,使用 subs 添加了一个自我文档的元素。通过创建一个三行子,可以替换

my $sum;
my $count;
for (@levels) {
   next if $_ >= 10;
   ++$count;
   $sum += $_;
}

my $avg = $sum / $count;

my $avg = avg grep $_ >= 10, @levels;

猜测“avg”的作用比一些循环要容易得多,而且您不会错过第二个版本中的过滤器。

顺便说一句,这个 subs 甚至适用于一小段代码,使用 subs 实际上可以减少代码,即使你只调用一次!在这种情况下,减少了两个非空行。

sub avg {
   my $acc;
   $acc += $_ for @_;
   return $acc / @_;
}

PS - 除了初始化代码之外,我避免将代码放在顶层。我将顶级代码放在块中以限制词汇的范围并分离关注点。

{
   my ($num_one, $num_two) = (1, 2);
   add($num_one, $num_two);
   subtract($num_one, $num_two);
}
于 2012-06-14T16:14:18.143 回答
4

You've pointed out that code is easier to reuse if it's in a subroutine. I think there are at least three other good reasons for using subroutines.

  1. If your subroutines are well-written (by which I mean that they don't use global variables, they have well-defined return points and they are small - certainly no more than a screen-full of code) then you can work on the code in the subroutine without caring about the rest of the code. And that makes your code easier to maintain.
  2. Well-named subroutines make your code easier to follow. If you main line of execution just calls half a dozen well-named subroutines then it is instantly obvious what your program does.
  3. Code in subroutines is far easier to test than code outside of subroutines. Even better if your subroutines are in a separate library. The test suite can just load the library and try each of the subroutines in turn, checking that it has the correct effect.

These points are obviously all simplifications. But they go some way towards explaining why the vast majority of my code is in subroutines.

于 2012-06-14T15:37:54.450 回答
2

是的,即使子例程只被调用一次,将程序分解为子例程也是一种很好的做法。因为它提高了可读性。想象一下,你有一个“for”循环或一个“if”语句,其中的代码超过三页或更多......逻辑流程变得更难理解。但是,如果您有子例程(调用其他子例程)-您的主循环或 main if .. 可能很容易放在一页上-更易于阅读,更易于维护。

还要考虑到今天该代码只被调用一次,但在 6 个月后您可能会看到需要重用它 - 在这种情况下,您可以简单地解除子例程。

所以是的,如果可能的话,总是使用子程序。

于 2012-06-14T15:42:38.143 回答
2

作为一般规则,如果您要多次重复一系列代码,请使用 sub。随着您的脚本或应用程序变得越来越复杂,您将在重构它以实现逻辑组织和可读性方面采取各种措施。提炼,提炼,提炼。:)

于 2012-06-14T15:24:36.173 回答