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

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.