1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86
| use strict;
use warnings;
use feature qw(:5.10);
use List::MoreUtils qw(each_array);
sub merge_col {
my ($col_name, $col_value, $columns) = @_;
if (!exists $columns->{$col_name}) {
# add a new column
$columns->{$col_name} = $col_value;
}
else {
my $existing_col = $columns->{$col_name};
if ($existing_col eq "--") {
# select current col (old was undetermined)
$columns->{$col_name} = $col_value;
}
elsif ($col_value ne "--") {
# select the dominant
}
}
}
sub load_table {
my ($result_tabref, $result_keyref, $file) = @_;
open my $TABLE, "<", $file or die "Can't open $file: $!";
chomp(my $line = <$TABLE>);
my ($test_key, @col_names) = split /\s+/, $line;
if (!@$result_tabref) {
# create the first row containing a test key and a hash of column names
my $column_number = 1;
push @$result_tabref, [ $test_key, { map { $_ => $column_number++ } @col_names } ];
}
else {
# complete the first row
my $columns = $result_tabref->[0]->[1];
my $column_number = 1 + keys %$columns;
$columns->{$_} = $column_number++ foreach grep !exists $columns->{$_}, @col_names;
}
#my $col_number = keys %{$result_tabref->[0]->[1]};
while (defined($line = <$TABLE>)) {
chomp $line;
my ($test_key, @col_values) = split /\s+/, $line;
if (exists $result_keyref->{$test_key}) {
# complete an existing row
my $columns = $result_tabref->[$result_keyref->{$test_key}]->[1];
my $col_index = 0;
foreach my $col_value (@col_values) {
merge_col($col_names[$col_index++], $col_value, $columns);
}
}
else {
# create a list of missing column values (from the column number of the first row)
my $col_index = 0;
push @$result_tabref, [ $test_key, { map { $col_names[$col_index++] => $_ } @col_values } ];
$result_keyref->{$test_key} = $#$result_tabref;
}
}
}
sub print_table {
my ($tabref, $file) = @_;
open my $OUT, ">", $file or die "Can't open $file: $!";
# First row contains column names and positions ($other_cols is a hash)
my ($first_col, $col_names) = @{shift @$tabref};
my @col_names = sort { $col_names->{$a} cmp $col_names->{$b} } keys %$col_names;
say { $OUT } join " ", $first_col, @col_names;
foreach my $row (@$tabref) {
# First row contains column names and positions ($col_values is a hash)
my ($test_key, $col_values) = @$row;
say { $OUT } join " ", $test_key, map $col_values->{$_} // "--", @col_names;
}
}
my (@table, %test_keys);
load_table(\@table, \%test_keys, "fic1.txt");
load_table(\@table, \%test_keys, "fic2.txt");
print_table(\@table, "fic3.txt"); |