Averages/Simple moving average: Difference between revisions
Content deleted Content added
→{{header|Perl}}: clean up code (this is not a golf contest!), fix small bug, and add usage demonstration |
→{{header|Perl}}: some more clarification and code clean-up |
||
Line 2,235: | Line 2,235: | ||
=={{header|Perl}}== |
=={{header|Perl}}== |
||
Using an initializer function which returns an anonymous closure which closes over an instance ''(separate for each call to the initializer!)'' of the lexical variables <code>$period</code>, <code>@list</code>, and <code>$sum</code>: |
|||
<lang perl>sub sma_generator { |
<lang perl>sub sma_generator { |
||
my $period = shift; |
my $period = shift; |
||
my (@ |
my (@list, $sum); |
||
return sub { |
return sub { |
||
my $number = shift; |
|||
push @list, $number; |
|||
$sum += $number; |
|||
$sum -= shift @list if @list > $period; |
|||
return $sum / @list; |
|||
} |
} |
||
} |
} |