in reply to split hash into two columns

my @keys = reverse sort {$hash{$a} <=> $hash{$b} || $a cmp $b} (keys % +hash); foreach my $i ( 0 .. int($#keys/2) ){ # printf "%s %s\n", @keys[$i, $i+int($#keys/2)+1]; # UPDATE: expanded to avoid 'uninitialized value' warning print $keys[$i]; my $j = $i+int($#keys/2)+1; print "\t" . $keys[$j] if $j <= $#keys; print "\n"; }

Replies are listed 'Best First'.
Re^2: split hash into two columns
by ikegami (Patriarch) on Mar 27, 2006 at 20:23 UTC
    Almost
    1 7 2 8 3 9 4 10 5 11 Use of uninitialized value in printf [...]. 6
    Maybe
    my @keys = sort { $hash{$b} <=> $hash{$a} || $b cmp $a } keys %hash; my $half = int($#keys / 2); printf "%s\t%s\n", @keys[$_, $_+$half] for 0 .. $half-1; printf "%s\n", $keys[$#keys] unless $#keys % 2;
      This is a bit more code than I thought. Why are all the examples of my hash being broken into an array? I'd have to imagine there's a way to calculate 1/2 of the hash or something because in the code above, it doesn't print the key and the value.

        Hash won't do since they are unordered. A list will do for

        1 2 3 4 5 6

        but an array is needed for

        1 4 2 5 3 6

        since you need to access elements out of order.

        As for not printing the key and the value, it's trivial to make the above print both the key and the value since you have both the key and the hash. The output you asked for wasn't clear, so we only included a minimal print.

        Update: Here it is:

        my @keys = sort { $hash{$b} <=> $hash{$a} || $b cmp $a } keys %hash; my $half = int($#keys / 2); printf "%s => %s\t%s => %s\n", $keys[$_ ], $hash{$keys[$_ ]}, $keys[$_+$half], $hash{$keys[$_+$half]} for 0 .. $half-1; printf "%s => %s\n", $keys[$#keys], $hash{$keys[$#keys]} unless $#keys % 2;