The key thing to do is to have your data sorted by your key (in this case the first column of your data). Then you only need to keep a small amount of data in memory.
By the way, in the case where the column headers of your input files are not all different (except for the first), your program's output depends on the order the files are named in the command line.
Here's one way to process the data. I haven't tested this at all except to check that it passes perl -c.
#!/usr/bin/perl -w
use strict;
use warnings;
my @fileHeaders;
my %usedHeaders;
my $sortname = "sortfile.tmp";
# If you have more than one disk, consider putting
# a disk different from most of your data.
# Beware of disk space.
open SORTFILE, ">", $sortname
or die "Cannot create $sortname: $!\n";
# first pass, write to sortfile
foreach my $filename (@ARGV) {
open GSE, "<", $filename
or die "Cannot open $filename: $!\n";
my $headerline = <GSE>;
chomp($headerline);
$headerline =~ s/\r$//;
my @thisfileHeaders = split /\t/, $headerline;
shift @thisfileHeaders;
push @fileHeaders, \@thisfileHeaders;
my $filekey = sprintf "%04d", $#fileHeaders;
while(<GSE>) {
y/\r//d;
s/^([^\t]*)/$1\t$filekey/;
print SORTFILE $_
or die "print SORTFILE failed: $!\n";
}
if ($. > 1) { # if any data past headers
$usedHeaders{$_}++ for @thisfileHeaders;
}
close GSE;
}
close SORTFILE
or die "close SORTFILE failed: $!\n";
# Yes, close can fail. Buffered I/O, for one thing
system("sort -o sortfile.tmp sortfile.tmp") == 0
or die "Sort failed!\n";
# second pass; consolidate data from multiple files
my $prevkey;
open SORTFILE, "<", $sortname
or die "Cannot open $sortname: $!\n";
my @samples = sort keys %usedHeaders;
print "Probe\t".join("\t",@samples)."\n";
my %data;
while (my $ligne = <SORTFILE>) {
chomp($ligne);
my @t = split(/\t/, $ligne);
my $probe = shift @t;
my $filenum = shift @t;
if (!$prevkey || $probe ne $prevkey) {
dumpdata();
$prevkey = $probe;
}
@data{@{$fileHeaders[$filenum]}} = @t;
}
dumpdata();
sub dumpdata {
if (defined($prevkey)) {
print "$prevkey\t", join("\t", @data{@samples}), "\n";
}
$data{$_} = "" for @samples;
#initialize to blanks so no warnings on printing undef
}
Update: small edits.
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.