[Wellington-pm] ? shorten an Perl snippet

Grant McLean grant at mclean.net.nz
Mon Aug 2 14:52:48 PDT 2010


On Tue, 2010-08-03 at 09:34 +1200, Dan Horne wrote:
> Without wanting to golf it, perhaps something like
> 
> my $product = 0;
> 
> for my $j (10 .. 59) {
>     $product += $split_line[$j][5];
> }
> 
> $product = $product/50;
> 
> You could divide by 50 inside the loop, but that might introduce too
> many rounding errors

That's certainly an improvement over the original code.

I'd also be inclined to put the code in a subroutine with a name that
made it clear what it was doing.  Also the List::Util module (which has
been included with Perl since 5.8) provides a few tools you could use,
for example:

  use List::Util qw(sum);

  $product1 = average_50d(@split_line);

  sub average_50d {
      my $sum = sum map { $_->[5] } @_[10..59];
      return $sum / 50;
  }

For that quantity of data it would be more efficient to pass it by
reference but I didn't want to clutter up the example.

Cheers
Grant



More information about the Wellington-pm mailing list