Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

How can you print a hash in a sorted list where it would break into X table columns/rows? I have a hash that is sorted a-z order and since it's so long it can't be printed one per line. It needs to be broken into 3 or 4 (let's say three for now) lines.

Let's say we have 100 keys. It would find the best divided number for our rows (since we want 3 rows the best it can do is 33 per row but the extra 1 or 2 would have to be printed in the first or second column.

Difficult thing is, it needs to be sorted A-Z for each column, not row. So it has to be

a e i b f j c g k d h l
instead of
a b c d e f
Anyone have ideas on how to do this? thanks!

Replies are listed 'Best First'.
Re: table sorting of hashes
by BrowserUk (Patriarch) on Jun 12, 2004 at 08:40 UTC
    #! perl -slw use strict; my @sorted = 'a'..'z'; our $COLS ||= 3; my $offset = int @sorted / $COLS; for my $s ( 0 .. $offset ) { print join' ', grep defined, @sorted[ map{ $s + ($offset * $_) + $_ } 0 .. $COLS - 1 ]; } __END__ P:\test>test -COLS=3 a j s b k t c l u d m v e n w f o x g p y h q z i r P:\test>test -COLS=4 a h o v b i p w c j q x d k r y e l s z f m t g n u P:\test>test -COLS=5 a g m s y b h n t z c i o u d j p v e k q w f l r x

    Examine what is said, not who speaks.
    "Efficiency is intelligent laziness." -David Dunham
    "Think for yourself!" - Abigail
Re: table sorting of hashes
by Roger (Parson) on Jun 12, 2004 at 05:59 UTC
    The idea is simple:

    First, build a two dimensional array -
    original array: a b c d e f g h i j k l m ... 2-d array: a b c d e f g h ...

    When you print your data:
    for $x (0..4) { for $y (0..4) { print $temp_array[$y][$x], "\t"; } print "\n"; }

    Translate this into perl and you get your simple program.

Re: table sorting of hashes
by fluxion (Monk) on Jun 12, 2004 at 06:59 UTC
    The logic still depends on dividing the array length by the number of columns to obtain an approximation of the max rows required, so it won't always work as expected. I don't see any clean way to circumvent such a dependence, so failsafes would have to be implemented for uneven division results to ensure proper execution.
    #!/usr/bin/perl use strict; my @sorted_list = qw(a b c d e f g h i j k l m n); my @new_list; my $cols = '3'; my $element = '0'; while ($element <= $#sorted_list) { for my $x (0..(@sorted_list / $cols)) { push @{$new_list[$x]}, $sorted_list[$element++]; } } for my $row (@new_list) { for (@{$row}) { print "$_ "; } print "\n"; } __END__ a f k b g l c h m d i n e j

    Roses are red, violets are blue. All my base, are belong to you.