http://www.perlmonks.org?node_id=643485

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

Hi, I have 2 files (both which are rather large) but with the same number of lines. What I would like to do is read the the first line from the first file, and then the first line from the second file, and compare the contents of the two lines. But all my previous experience with filehandles in perl, I have while loops that read one file at a time. I can't seem to work around this. Can you guys point me in the right direction? Thanks for your help. ****** wait I think I got it:
#!/usr/bin/perl -w + + + use Data::Dumper; open(FILE1, $ARGV[0]); open(FILE2, $ARGV[1]); while ($line = <FILE1>) { my $line2= <FILE2>; chomp($line); chomp($line2); print "$line $line2\n"; }

Replies are listed 'Best First'.
Re: reading lines from 2 different files
by duff (Parson) on Oct 08, 2007 at 15:41 UTC

    Something like this:

    # assuming you've got the files open in handles $fh1 and $fh2 while (1) { last unless defined($line_from_file_1 = <$fh1>); last unless defined($line_from_file_2 = <$fh2>); # ... }

    Basically you just use the "read a record" operator (<>, aka diamond operator) on each file handle. See also readline.

Re: reading lines from 2 different files
by philcrow (Priest) on Oct 08, 2007 at 16:02 UTC
Re: reading lines from 2 different files
by toolic (Bishop) on Oct 08, 2007 at 15:44 UTC
    If you want to compare all lines of the 2 files, just like the unix "diff" command (or "tkdiff"):
    use warnings; use strict; open my $fh1, '<', 'file1.txt' or die "Can not open file1.txt $!\n"; open my $fh2, '<', 'file2.txt' or die "Can not open file2.txt $!\n"; while (<$fh1>) { chomp; my $line_f2 = <$fh2>; chomp $line_f2; if ($_ ne $line_f2) { print "Mismatch at line $.\n"; print "file1: $_, file2: $line_f2\n"; } } close $fh2; close $fh1;
      Your code silently ignores extra lines in file2.
        Yes, I realize that, but thanks for explicitly pointing it out. The OP stated that the 2 files have the "same number of lines". So, I presumed that the OP would be checking that ahead of time.
Re: reading lines from 2 different files
by mwah (Hermit) on Oct 08, 2007 at 15:59 UTC
    my @Fn = qw' bigfile1.txt bigfile2.txt '; open my $f1, '<', $Fn[0] or die "$Fn[0] $!"; open my $f2, '<', $Fn[1] or die "$Fn[1] $!"; while( defined(my $l1 = <$f1>) && defined(my $l2 = <$f2>)) { # chomp here, but only if necessary print "line $. is ", $l1 cmp $l2 ? "different!" : "identical!", " +\n" } close $f1, close $f2;
    Regards

    mwa
Re: reading lines from 2 different files
by roboticus (Chancellor) on Oct 08, 2007 at 21:54 UTC
    indapa:

    By your hashbang line, it appears that you're on a unix box, so you might try:

    paste file1 file2 >outfile

    ...roboticus

A reply falls below the community's threshold of quality. You may see it by logging in.