FoxtrotUniform has asked for the wisdom of the Perl Monks concerning the following question:
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?
|
---|
Replies are listed 'Best First'. | |
---|---|
Re: Fun with two-dimensional arrays
by suaveant (Parson) on Aug 09, 2001 at 21:00 UTC | |
by FoxtrotUniform (Prior) on Aug 09, 2001 at 21:07 UTC | |
by suaveant (Parson) on Aug 09, 2001 at 21:13 UTC | |
Re: Fun with two-dimensional arrays
by bikeNomad (Priest) on Aug 09, 2001 at 21:04 UTC | |
by FoxtrotUniform (Prior) on Aug 09, 2001 at 21:14 UTC | |
by George_Sherston (Vicar) on Aug 10, 2001 at 04:59 UTC | |
by bikeNomad (Priest) on Aug 09, 2001 at 21:23 UTC | |
(tye)Re: Fun with two-dimensional arrays
by tye (Sage) on Aug 10, 2001 at 01:49 UTC | |
Re: Fun with two-dimensional arrays
by arturo (Vicar) on Aug 09, 2001 at 21:01 UTC |