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.
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:
$vscr[$x][$y];
The question was, how do you traverse this array row by row? The obvious answer,
traverses the screen in the wrong order.foreach my $x (@vscr) { foreach my $y (@$x) { &do_stuff($y); } }
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:
(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.)foreach my $row (0..21) { foreach my $col (@vscr) { &do_stuff($col[$row]); } }
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?
In reply to Fun with two-dimensional arrays by FoxtrotUniform
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |