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


In reply to Re: Refactor this to eliminate the duplicated printf? by davido
in thread Refactor this to eliminate the duplicated printf? by wanna_code_perl

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.