perlquestion
FoxtrotUniform
<p>So I'm the resident Perl Answer Guy at my orkplace (not that I'm the best Perl hacker here, but those better than I are either busy doing other stuff, like running the network, or just don't like answering questions). I got an interesting one the other day, and it's still bugging me.</p>
<p>My colleague had a 2d array simulating a textmode screen. 22 rows, 80 columns; however, he wanted to write to the "screen" first, then worry about over-long lines, so each row could have more than 80 chars in it. He had it
set up like so:<br>
<code>
$vscr[$x][$y];
</code></p>
<p>The question was, how do you traverse this array row by row? The obvious answer,<br>
<code>
foreach my $x (@vscr) {
foreach my $y (@$x) {
&do_stuff($y);
}
}
</code>
traverses the screen in the wrong order.</p>
<p>My first suggestion was to switch the order of x and y
in the array; this isn't quite as intuitive for accesses,
but makes the obvious traversal DTRT. But this bugged me:
after all, TMTOWTDI, right? So I came up with this:<br>
<code>
foreach my $row (0..21) {
foreach my $col (@vscr) {
&do_stuff($col[$row]);
}
}
</code>
(At this point, he has changed the order of x and y in the array, so this code never got used, which means it's
untested and probably broken.)</p>
<p>This isn't so much worse than the obvious nested foreach
approach, but it bugs me that the number of rows is hard
coded. Is there a more general way to do this that's still
fairly clean?</p>