in reply to split hash into two columns

An alternative:
my @keys = sort { $hash{$b} <=> $hash{$a} || $b cmp $a } keys %hash; my @col1 = splice(@keys, 0, $#keys/2+1); my @col2 = @keys; while (@col2) { my $key1 = shift(@col1); my $key2 = shift(@col2); printf "%s => %s\t%s => %s\n", $key1, $hash{$key1}, $key2, $hash{$key2}; } while (@col1) { my $key1 = shift(@col1); printf "%s => %s\n", $key1, $hash{$key1}; }

Updated and tested.

Incorrect original version:

my @col1; my @col2; my $t = 0; foreach (sort {$hash{$b} <=> $hash{$a} || $b cmp $a} keys %hash) { if ($t ^= 1) { push(@col1, $_); } else { push(@col2, $_); } } printf "%s\t%s\n", pop(@col1), pop(@col2) while @col2; printf "%s\n", pop(@col1) while @col1;

Replies are listed 'Best First'.
Re^2: split hash into two columns
by Anonymous Monk on Mar 27, 2006 at 23:15 UTC
    Hi.

    2 questions for you. I modified this code so I could save all the data.

    What is $t ^= 1 doing? I've never seen ^= before.

    Secondly, this is resulting in the data being separated from left to right order, not verticle.

    10 9 8 7 6 5 4 3
    instead of
    10 5 9 4 8 3 7 2 6 1
    How can I change it? Thanks!

      Oops! Fixed in original node. I also made the code print both the keys and the values.

      $a ^= $b is a shortcut for $a = $a ^ $b. Both operators are documented in perlop. In context, $t ^= 1 causes $t and the return value of the expression to flip-flip between zero and one every time it is executed (assuming $t is originally zero or one).