Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask

Re: How do you create a tab delimited txt file from two files?

by almut (Canon)
on Jul 29, 2010 at 08:01 UTC ( #851870=note: print w/replies, xml ) Need Help??

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

Open the two files, then read a line from each file on every iteration:

while (my $col1 = <FILE1>) { chomp $col1; my $col2 = <FILE2>; print "$col1\t$col2"; }

Replies are listed 'Best First'.
Re^2: How do you create a tab delimited txt file from two files?
by elef (Friar) on Jul 29, 2010 at 08:17 UTC

    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?
      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]


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

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://851870]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others meditating upon the Monastery: (7)
As of 2018-03-17 14:35 GMT
Find Nodes?
    Voting Booth?
    When I think of a mole I think of:

    Results (224 votes). Check out past polls.