Neuroactive has asked for the wisdom of the Perl Monks concerning the following question:

How do I combine two lists, each from a different document, so that the contents get printed side-by-side in another document?

List A List 1 Combo A1 A 1 A 1 B 2 B 2 C 3 C 3

I'm doing a lot of processing of the data from these files, as well. I just don't know how to read and print data, line-by-line, from two different source files.

Thanks!

Replies are listed 'Best First'.
Re: Combining Lines from Two Docs into Another
by Limbic~Region (Chancellor) on Jul 20, 2004 at 23:40 UTC
    Neuroactive,
    I just don't know how to read and print data, line-by-line, from two different source files.

    That's not the hard part. The hard part is doing "the right thing" if the files do not have the same number of lines. Oh, and if these were arrays - you might want to look at tye's Algorithm::Loops - specifically mapcar. FWIW - you can read a file into an array pretty easily using the syntax my @array = <FILEHANDLE>; # just remember you have slurped the entire file into memory.

    #!/usr/bin/perl use strict; use warnings; my $file1 = $ARGV[0] || 'file1.txt'; my $file2 = $ARGV[1] || 'file2.txt'; open (FILE1, '<', $file1) or die "Unable to open $file1 for reading : +$!"; open (FILE2, '<', $file2) or die "Unable to open $file2 for reading : +$!"; while ( <FILE1> ) { chomp; my $foo = <FILE2>; $foo = 'N/A' if eof FILE2; print join "\t" , $_ , $foo; print "\n"; } while ( <FILE2> ) { chomp; print join "N/A\t$_\n"; }

    Cheers - L~R

Re: Combining Lines from Two Docs into Another
by ysth (Canon) on Jul 21, 2004 at 00:16 UTC
    The same way you do it for one file, only reading two instead. It would be nice to see what you've tried, so as to be able to help with whatever is your sticking point.
    open FILEA, "< filea.txt" or die "Error opening filea.txt: $!"; open FILE1, "< file1.txt" or die "Error opening file1.txt: $!"; open FILEOUT, "> fileout.txt" or die "Error opening fileout.txt: $!"; while ( defined( my $lineA = <FILEA> ) && defined( my $line1 = <FILE1> + ) { chomp( $lineA, $line1 ); print FILEOUT "$lineA $line1"; } die "Eek!" if defined( $lineA ) || defined( $line1 );
Re: Combining Lines from Two Docs into Another
by dmorgo (Pilgrim) on Jul 20, 2004 at 23:32 UTC
    I hate to give a non-Perl answer to a question here, but if you are on Unix, you can do:

    paste file1 file2

      See also man join if you need to get fancy in how you combine.

Re: Combining Lines from Two Docs into Another
by pbeckingham (Parson) on Jul 21, 2004 at 00:39 UTC

    Assumes that file1.txt and file2.txt contain the same number of lines.

    #! /usr/bin/perl -w use strict; open (my $file1, '<', 'file1.txt') or die $!; open (my $file2, '<', 'file2.txt') or die $!; while (my $line1 = <$file1>) { chomp $line1; my $line2 = <$file2>; print $line, ' ', $line2; } close $file1; close $file2;
    Update: Code correction.