Use a negative width to left-justify. For example,
"%5s" means pad to 5 characters, right-justified.
"%-5s" means pad to 5 characters, left-justified.
The following are not the most compact solutions, but they are probably the most readable. Don't forget that programs should be written for those who maintain them.
Untransposed:
use strict; use warnings; use List::Util qw( max ); use POSIX qw( ceil ); my @a = qw(un deux trois quatre jedan dva tritcheteri one two three); my $cols = 4; my $width = (max map length, @a) + 1; my $rows = ceil(@a / $cols); for my $r (0..$rows-1) { for my $c (0..$cols-1) { next if (my $i = $r * $cols + $c) > $#a; printf('%-*s', $width, $a[$i]); } print("\n"); }
Transposed:
use strict; use warnings; use List::Util qw( max ); use POSIX qw( ceil ); my @a = qw(un deux trois quatre jedan dva tritcheteri one two three); my $cols = 3; my $width = (max map length, @a) + 1; my $rows = ceil(@a / $cols); for my $r (0..$rows-1) { for my $c (0..$cols-1) { next if (my $i = $r + $c * $rows) > $#a; printf('%-*s', $width, $a[$i]); } print("\n"); }
Now, wouldn't it be nice if each column was as narrow as possible? There's gotta be a module to do that on CPAN, but I didn't find one quickly.
Update: I had to leave before I could finish writting my entire node. Here's the rest.
Update: Fixed a bug in "Transposed". Thanks to jhourcle for pointing it out.
In reply to Re: Printing an array columnwise or rowwise
by ikegami
in thread Printing an array columnwise or rowwise
by logen
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |