02:17 02:40 02:46 02:59 Apples 0 0 0 0 Grapes 7 7 7 7 bricks 0 0 0 0 TUBELIGHS 282 271 265 257 TOTAL 289 278 272 264
If you want to do this using good ol' printf, which nobody has suggested (but was part of your original post), here is how I would do it:
#!/usr/bin/perl -w # Strict use strict; use warnings; # Assign variables my $plabels = [ '02:17', '02:40', '02:46', '02:59' ]; my $pcounts = { 'Apples' => [ 0, 0, 0, 0, ], 'Grapes' => [ 7, 7, 7, 7, ], 'bricks' => [ 0, 0, 0, 0, ], 'TUBELIGHS' => [ 282, 271, 265, 257, ], }; my $p_ordered = [ qw( Apples Grapes bricks TUBELIGHS ) ]; my $ncols = 4; # Or $ncols = scalar @{$pcounts->{$p_ordered->[0]} +}; # Calculate totals my $pTOTAL = [ ]; foreach my $key (keys %$pcounts) { map { $pTOTAL->[$_] += $pcounts->{$key}->[$_] } (0..$ncols-1); } # Main program print_row("", $plabels, " %7.7s"); map { print_row($_, $pcounts->{$_}, " %7d") } @$p_ordered; print "\n"; print_row("TOTAL", $pTOTAL, " %7d"); # Subroutines sub print_row { my ($label, $pvalues, $format) = @_; printf " %-12.12s", $label; map { printf $format, $_ } @$pvalues; print "\n"; }
Note that by using a subroutine print_row, you achieve a couple of things. First, it greatly simplifies the main program down to just several lines. And secondly, it lets you change the width of each item in the output, just by changing the format passed to the subroutine (eg. change " %7.7s" to " %-7.7s" to left-justify the labels, or change " %7.7s" and " %7d" to " %8.8s" and " %8d" respectively, to increase the width of each item to 8 characters).
PS. What the heck is a "TUBELIGH"? :)
In reply to Re: arrange columns
by liverpole
in thread arrange columns
by Anonymous Monk
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |