in reply to Re^2: making presence/absence table from a hash of arrays
in thread making presence/absence table from a hash of arrays
See code below. Perl is great at translating one thing into another thing - the hash table. So I just make a hash table table to translate the column name into an array index. This also perhaps could have been just statically declared, but I wanted to make this flexible. For each row in the table, I just zero out an array and use the name2Index translator to turn on the appropriate elements and then print that row.
#!/usr/bin/perl -w use strict; use Data::Dump qw(pp); my $header_row= 'one two three four five'; my %table = ( row_1 => [qw(one five two)], row_2 => [qw(four two)], row_3 => [qw(three one five four)], ); my %name2Index; my $col=0; foreach my $col_head (split ' ',$header_row) { $name2Index{$col_head} = $col++; } print "name2Index table = ",pp(\%name2Index),"\n\n"; foreach my $row (sort keys %table) { my @bitmap = (0) x keys %name2Index; foreach my $col_name (@{$table{$row}}) { $bitmap[$name2Index{$col_name}] = 1; } print "$row = @bitmap\n"; } __END__ name2Index table = { five => 4, four => 3, one => 0, three => 2, two = +> 1 } row_1 = 1 1 0 0 1 row_2 = 0 1 0 1 0 row_3 = 1 0 1 1 1
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^4: making presence/absence table from a hash of arrays
by jwkrahn (Abbot) on Sep 06, 2011 at 17:02 UTC | |
by Anonymous Monk on Sep 06, 2011 at 22:08 UTC | |
by Marshall (Canon) on Sep 06, 2011 at 22:47 UTC | |
by jwkrahn (Abbot) on Sep 06, 2011 at 22:57 UTC | |
by Marshall (Canon) on Sep 07, 2011 at 03:45 UTC |