wanna_code_perl has asked for the wisdom of the Perl Monks concerning the following question:
Here's a simplified version of a pattern I come across every so often that bugs me: you're reading from a stream of unknown length, you need to do "something" at every Nth iteration, and N is pretty much never an even divisor, so there are always leftovers, which makes for a clumsy re-use of the "something", like so:
use 5.014; use warnings; my ($sum, $count) = (0,0); while (<DATA>) { $sum += $_; $count++; if ($count == 5) { printf "Sum: %4d, count: %2d, mean: %5.1f\n", $sum, $count, $sum/$count; $sum = 0; $count = 0; } } printf "Sum: %4d, count: %2d, mean: %5.1f\n", $sum, $count, $sum/$count; __DATA__ 61 23 30 444 368 438 467 44 812 430 992 469
This outputs:
Sum: 926, count: 5, mean: 185.2 Sum: 2191, count: 5, mean: 438.2 Final Sum: 1461, count: 2, mean: 730.5
Often, the "something" (the printf in my example, but could be a few statements in length) doesn't warrant putting it into a sub (and paying the function call overhead every Nth time through the main loop), but neither do I like having to copy/paste it just to catch the leftovers after the loop exit.
Is there a good way to refactor this so I don't have to repeat the printf, without sticking it in a sub?
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Refactor this to eliminate the duplicated printf?
by davido (Cardinal) on Jul 14, 2014 at 04:03 UTC | |
by wanna_code_perl (Friar) on Jul 14, 2014 at 06:50 UTC | |
by Anonymous Monk on Jul 14, 2014 at 20:23 UTC | |
|
Re: Refactor this to eliminate the duplicated printf?
by wjw (Priest) on Jul 14, 2014 at 04:18 UTC | |
by wanna_code_perl (Friar) on Jul 14, 2014 at 06:00 UTC | |
|
Re: Refactor this to eliminate the duplicated printf?
by redbull2012 (Sexton) on Jul 14, 2014 at 06:42 UTC | |
by wanna_code_perl (Friar) on Jul 14, 2014 at 06:59 UTC | |
| A reply falls below the community's threshold of quality. You may see it by logging in. |