elef has asked for the wisdom of the Perl Monks concerning the following question:
I'd like to have a perl script create a tab delimited txt out of two text files, line by line.
I.e. I have:And I'd like the script to generate:File 1: one two three four File 2: A B C D
one[tab]A two[tab]B three[tab]C four[tab]D
Ideally, this would be done without reading any of the files into memory in full, as I'd like it to work on large files on systems with little memory. (Although I'd like to know how it's best done by reading the files into variables, God knows I need some guidance on arrays and the like.)
I feel like some sort of a while loop should work, but it would need to iterate through two files at once, which sounds tricky... Maybe I could create a while loop that goes through file 1, saves the current line no. and the current line content in variables, and embed another while loop in it that goes through file 2 and prints the output when it gets to the line number that loop 1 is at. That should work, but that way I'd loop through file 2 lots of times.Any ideas for doing this in a more elegant/efficient way?
Update: solved, my favourite solution for files of equal length is (from almut):And, if the two files may have a different number of lines, courtesy of BrowserUk and Marshall:while (my $col1 = <FILE1>) { chomp $col1; my $col2 = <FILE2>; print "$col1\t$col2"; }
until(eof(ONE) and eof (TWO)) { my $one = <ONE>; my $two = <TWO>; $one ||= ""; $two ||= ""; chomp($one); chomp($two); print "$one\t$two\n"; }
|
|---|