http://qs1969.pair.com?node_id=158356

FoxtrotUniform has asked for the wisdom of the Perl Monks concerning the following question:

Monks,

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:

# current output directive: v0 v1 v2 v3 v4 v5 # desired output directive: v0 v1 v2 v3 directive: v4 v5

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:

print "directive: "; for my $var (@vars) { print munge_var($var), " "; } print "\n";
and hacked on some counting:
my $v_count = 0; print "directive: "; for my $var (@vars) { print &munge_vars($var), " "; $v_count++; if($v_count == $LIMIT) { print "\ndirective: "; $v_count = 0; } } print "\n";

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:

my $v_count = 0; for my $var (@vars) { if(($v_count % $LIMIT) == 0) { print "\ndirective: "; } print &munge_var($var), " "; } print "\n";

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....)

--
Good luck, tilly
:wq