How to print list as matrix
Angharad
created: 2006-08-04 10:14:33
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
Re: How to print list as matrix
created: 2006-08-04 10:21:02

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
created: 2006-08-04 10:23:35

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 [Fletch|PonyMaster].

Another Update: Note that [Albannach]'s solution [node://565673|below] is better, since it allows for holes in the inner hash.


No good deed goes unpunished. -- (attributed to) Oscar Wilde
Re: How to print list as matrix
created: 2006-08-04 10:38:41
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() {
  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

perlmonks.org content © perlmonks.org and Albannach, Angharad, Fletch, ptum

prlmnks.org © 2006 edmund von der burg (eccles & toad)

v 0.03