|The stupid question is the question not asked|
Breaking output lines into N-element chunksby FoxtrotUniform (Prior)
|on Apr 11, 2002 at 16:33 UTC||Need Help??|
FoxtrotUniform has asked for the
wisdom of the Perl Monks concerning the following question:
I've recently been asked to make some changes to a script I wrote several months ago. The script generates an input file for a statistics package we use, and as we discover limitations in the package, the script has to be changed. The problem isn't terribly difficult: the script outputs lines of arbitrary length (for this problem, length is measured in variables, not characters), and must be modified to output lines of N variables or fewer. So if N is 4:
Not terribly difficult. But these projects are usually refactors, not rewrites, and need to be done MFP. So mucking with the data structure isn't an option. What I've done so far is to convert a simple:
and hacked on some counting:
Ugh. But it gets the job done, even early in the morning before my first cup of coffee.
Always looking for more elegance, I'm contemplating this technique for the next time this comes up:
A bit cleaner, but outputs a leading newline, and the mod in the conditional might mess up a maintainance programmer (I've seen it happen before).
The "hey, there's a leading separator that shouldn't be there" problem that I noticed above makes me think that I should be keeping a list of lines, and doing a print join("\n", @lines), "\n"; at the bottom of the loop. All of my attemts to write a list- based solution end up being three or four times longer and harier than either of the above, though.
TIMTOADY, but how would you do it? I'm sure there's a cleaner solution to this problem than I've seen. What am I missing? (Besides a decent title on this node, that is....)