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?
In reply to Refactor this to eliminate the duplicated printf? by wanna_code_perl
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |