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

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.