Align columns: Difference between revisions

m
(C# code)
Line 1,068:
print "\n" ;
}
</lang>
or more succinctly
<lang perl>
use List::Util qw/max/;
 
sub columns {
my @lines = map [split /\$/] => split /\n/ => shift;
local $_ = shift;
for my $col (0 .. max map $#$_ => @lines) {
my $max = max my @widths = map length $lines[$_][$col] => 0 .. $#lines;
for $row (0 .. $#lines) {
my $pad = ($max - $widths[$row]) / 2;
$lines[$row][$col] = join '' =>
($lines[$row][$col], ' ' x $pad, ' ' x ($pad + 0.5))
[ /center/ ? (1,0,2) : /right/ ? (1,2,0) : (0,1,2) ]
}
}
join '' => map {"@$_\n"} @lines
}
 
print columns <<'END', $_ for qw/left right center/;
Given$a$text$file$of$many$lines,$where$fields$within$a$line$
are$delineated$by$a$single$'dollar'$character,$write$a$program
that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$
column$are$separated$by$at$least$one$space.
Further,$allow$for$each$word$in$a$column$to$be$either$left$
justified,$right$justified,$or$center$justified$within$its$column.
END
</lang>