#!/usr/bin/perl use strict; use warnings; use List::Util qw/ max /; my @matrix; my $path = '.'; # (current directory - '.') or path to data files my @file = qw/list.txt one.txt another.txt/; for my $file ( @file ) { my %data; my @substrate; open my $fh, "<", "$path/$file" or die "Unable to open $file for reading. $!"; while (<$fh>) { if (/^substrate/) { @substrate = /\d+/g; } elsif (/^product/) { while (/(\d+)/g) { for my $sub (@substrate) { $data{$sub}{$1} = 1 ; } } } else { die "Unknown format $file. $!"; } } close $fh or die "Unable to close $file. $!"; print "Processing file: $file\n"; process(%data); push @matrix, \%data; } for my $i (0 .. $#matrix) { for my $j ($i+1 .. $#matrix) { print "Combining $file[$i] and $file[$j]\n"; my %data = combine($matrix[$i], $matrix[$j]); process(%data); } } sub process { my %data = @_; my %seen; my @product = sort {$a <=> $b} grep ! $seen{$_}++, map keys %$_, values %data; # to get column width for print my $wid = 1 + max map length, @product; printf "%7s" . "%${wid}s" x @product . "\n", 'prod->', @product; for my $substrate (sort {$a <=> $b} keys %data) { printf "%7s", $substrate; printf "%${wid}s", $data{$substrate}{$_} || '-' for @product; print "\n"; } printf "\n%5s\n%5s\n%s\n\n", '^', '|', 'substrate'; } sub combine { my ($matrix1, $matrix2) = @_; my %new_hash = %$matrix1; for my $substrate (keys %$matrix2) { $new_hash{$substrate}{$_} = 1 for keys %{ $matrix2->{$substrate} }; } return %new_hash; }