You could first save the data from the second file in a hash with the first column as a key, and then retrieve that data from the hash as you're going over the lines from the first file. The following code assumes that the first columns in the two files are identical (string-wise). Also this will read the entire second file into memory, so it might not be too great if your second file becomes huge.
# ... snip opening the files ... my %file2data; while(<$input_file2>) { next if /(^\s*$)|(^#)|(^@)/; my @columns2 = split; $file2data{$columns2[0]} = $columns2[1]; } while(<$input_file1>) { next if /(^\s*$)|(^#)|(^@)/; my @columns1 = split; print $out_file join("\t", $columns1[0],$columns1[1], $file2data{$columns1[0]}), "\n"; }
This will produce your expected output.
Note that if you're going to be manipulating a lot of files like this, then investing the time into learning Text::CSV will probably be worth it. Also, if your dataset is large, this is the kind of operation that a database would handle well.
In reply to Re: Adding some columns into a file from two files using perl
by Anonymous Monk
in thread Adding some columns into a file from two files using perl
by perlselami
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |