in reply to Re: How do you create a tab delimited txt file from two files?
in thread How do you create a tab delimited txt file from two files?

Ooooh, that's nice, I had no idea perl could do that. This is the sort of thing I was looking for.

One issue, though: it seems to choke if the two files don't have the same number of lines. I could just count the lines in each and pad the shorter file with as many \n as required before starting the loop, but there has to be a better solution than that. Any tips?
  • Comment on Re^2: How do you create a tab delimited txt file from two files?

Replies are listed 'Best First'.
Re^3: How do you create a tab delimited txt file from two files?
by Utilitarian (Vicar) on Jul 29, 2010 at 08:47 UTC
    while (my $col1 = <FILE1>) { chomp $col1; last unless (my $col2 = <FILE2>); print "$col1\t$col2"; }
    the above will stop at the end of the shorter file
    print "Good ",qw(night morning afternoon evening)[(localtime)[2]/6]," fellow monks."

      FWIW this can be written in Perl 6 very nicely:

      $ perl6 -e 'for lines("a") Z lines("b") -> $a, $b { say "$a\t$b" }'

      Where "a" and "b" are the names of the two files.

      If the iteration should not stop after the second file is exhausted, we can pad the lines of the second file with an infinite number of empty strings:

      $ perl6 -e 'for lines("a") Z lines("b"), '' xx * -> $a, $b { say "$a\t +$b" }'

      Works with Rakudo today.

      Perl 6 - links to (nearly) everything that is Perl 6.
      Well, that's better than what the original script does, but I'd prefer to have the end of the longer file in the output as well, paired with empty "cells".

      I.e. either

      bla[tab] bla[tab] bla[tab]

      or

      [tab]bla [tab]bla [tab]bla
        A slight mod to BrowserUk's code is what you need:
        #!/usr/bin/perl -w use strict; open ONE, '<', "one.txt" or die "First File: $!\n"; open TWO, '<', "two.txt" or die "Second File: $!\n"; until( eof( ONE ) and eof (TWO)) { my $one = <ONE>; my $two = <TWO>; $one ||= ""; $two ||= ""; chomp($one); chomp($two); print "$one\t$two\n"; } __END__ OUTPUT: a this is 0 file two ab dsf one.txt: a 0 ab dsf two.txt: this is file two