in reply to arrange columns

It looks like the format of your data in the final section "How can I correct the code so that my output is clean" is still fairly garbled.  I'll assume that you wanted things lined up like:
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"? :)


s''(q.S:$/9=(T1';s;(..)(..);$..=substr+crypt($1,$2),2,3;eg;print$..$/

Replies are listed 'Best First'.
Re^2: arrange columns
by ambrus (Abbot) on Jul 29, 2006 at 23:33 UTC
    It looks like the format of your data in the final section "How can I correct the code so that my output is clean" is still fairly garbled. I'll assume that you wanted things lined up like:
    If you download the code and view it with tab width 8, it will show up correctly. It doesn't in the node as perlmonks has a simpler idea about displaying tab characterss in code tags than is required here.