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 (@a, $sum);
my (@list, $sum);

return sub {
return sub {
unshift @a, shift;
my $number = shift;
$sum += $a[0];
push @list, $number;
@a > $period and $sum -= pop @a;
$sum += $number;
return $sum / @a;
$sum -= shift @list if @list > $period;
return $sum / @list;
}
}
}
}