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

Hi there I have a list which looks like this
object1 object1 78 object1 object2 45 object1 object3 34 object1 object4 45 object2 object2 89 object2 object3 32 object2 object4 13
etc
And I would like to rearrange it so it looks like this
object1 object2 object3 object4 object1 78 45 34 45 object2 45 89 32 13
I would be most grateful if someone could point me in the right direction as my attempts have been pretty shambolic so far. Thanks

Replies are listed 'Best First'.
Re: How to print list as matrix
by Albannach (Monsignor) on Aug 04, 2006 at 14:38 UTC
    I noticed in your data there is no object2,object1 value in contradiction with your output sample, but with that in mind I'd elect to assume that not all cells in the table will necessarily be defined, and so you may need to inspect all the data to discover all the possible column names.
    use strict; use warnings; my %table; my %rows; my %cols; for(<DATA>) { my($row,$col,$val) = split ' '; $table{$row}{$col} = $val; $rows{$row}++; $cols{$col}++; } for my $col (sort keys %cols) { print "\t$col"; } print "\n"; for my $row (sort keys %rows) { print "$row\t"; for my $col (sort keys %cols) { print $table{$row}{$col} if defined $table{$row}{$col}; print "\t"; } print "\n"; } __DATA__ object1 object1 78 object1 object2 45 object1 object3 34 object1 object4 45 object2 object2 89 object2 object3 32 object2 object4 13

    --
    I'd like to be able to assign to an luser

Re: How to print list as matrix
by Fletch (Bishop) on Aug 04, 2006 at 14:21 UTC

    Build a hash of hashes (see perldsc) with the first hash keyed off the first column, the second level keyed off the second, and the value being the third. Then for each item in keys %hash print out the values for each of keys %{$hash{ $first }}.

Re: How to print list as matrix
by ptum (Priest) on Aug 04, 2006 at 14:23 UTC

    How 'bout a hash of hashes, step through them with a nested for loop (code untested)?

    my %outer = (); $outer{object1}->{object1} = 78; $outer{object1}->{object2} = 45; ... $outer{object2}->{object4} = 13; foreach my $outer_key (sort keys %outer) { print $outer_key, "\t"; foreach (sort keys %{$outer{$outer_key}}) { print $outer{$outer_key}->{$_}, "\t"; } print "\n" }

    Update Man! A monk sure has to be quick to beat out the PonyMaster.

    Another Update: Note that Albannach's solution below is better, since it allows for holes in the inner hash.


    No good deed goes unpunished. -- (attributed to) Oscar Wilde