in reply to Refactor this to eliminate the duplicated printf?

Use eof to determine if the next read will fail due to end of file. Here's an example. This is just a demonstration rather than a refactoring of your code. But the technique would prove to adapt to your code in a straightforward way.

while( my $line = <DATA> ) { print $line if $. % 5 == 0 || eof(\*DATA); } __DATA__ line one line two line three line four line five line six line seven line eight line nine line ten line eleven

Output:

line five line ten line eleven

Update: Here is a revision of your original code that handles end-of-file correctly without duplicating your printf statements:

my ($sum, $count) = (0,0); while (<DATA>) { $sum += $_; $count++; if ($count == 5 || eof(\*DATA) ) { printf "Sum: %4d, count: %2d, mean: %5.1f\n", $sum, $count, $sum/$count; $sum = 0; $count = 0; } } __DATA__ 61 23 30 444 368 438 467 44 812 430 992 469

I provided this to show that a solution that eliminates code repetition needn't be complicated or illegible. I literally changed only two things; one, removed 'printf' outside of the loop; and two, added || eof(\*DATA) to your if conditional.

Philosophically your goal is worthwhile. Today, perhaps it's just a printf. Tomorrow it could grow to a few lines. And the next day you might alter the format string and parameters of the printf. Suddenly you find yourself needing to make the change in two places instead of one, and possibly get one of those changes wrong. It just makes sense; if you can avoid repetition without making the code illegible or grossly inefficient, seek to do so.


Dave

Replies are listed 'Best First'.
Re^2: Refactor this to eliminate the duplicated printf?
by wanna_code_perl (Friar) on Jul 14, 2014 at 06:50 UTC

    Thank you davido. I had a chance to try this with the full code and, no surprise, it indeed does the trick! I'll be adding this little idiom to my bag of tricks.

Re^2: Refactor this to eliminate the duplicated printf?
by Anonymous Monk on Jul 14, 2014 at 20:23 UTC

    A minor nitpick: the control flow is not exactly the same in the OP and the revised version. The difference is with empty input, where the OP code would still print something (or divide by zero).