Comparing values in 2 textfiles and returning the missing values

Discussion in 'Perl' started by Jorgen Gustafsson, Dec 11, 2003.

  1. Hi,
    im trying to write a small progam to compare data in 2 textfiles.

    I want to search for values that doesnt exist in File2.
    The result should be "3" in the example below but Im not
    able to do this since my program crosschecks all numbers in
    both files and Im getting a lot of "hits". (outer and inner while-loops)


    Below is an examples of the textfiles:

    File1.txt File2.txt
    1 1
    2 2
    3 4
    4 5
    5 6
    7
    8
    9
    10

    Thanks in advance...!
    Jorgen
     
    Jorgen Gustafsson, Dec 11, 2003
    #1
    1. Advertisements

  2. Jorgen Gustafsson

    Jim Gibson Guest

    If you have a program written, it is best to include that in your post.

    If your files are short enough, you can try reading file 2 first and
    creating a hash with the values from file 2 as keys (the value of the
    hash doesn't matter, so set it to 1 or increment to get a count). Then,
    read file 1 and see if the corresponding keys exist in your hash.

    Here's a quick sample program (with two files appended and separated by
    a BREAK line):

    #!/opt/perl/bin/perl

    use strict;
    use warnings;

    my %seen;
    while(<DATA>) {
    chomp;
    last if /BREAK/;
    $seen{$_}++;
    }

    while(<DATA>) {
    chomp;
    if( ! $seen{$_} ) {
    print "$_ not in file 1\n";
    }
    }

    __DATA__
    1
    2
    4
    5
    6
    7
    8
    9
    10
    BREAK
    1
    2
    3
    4
    5

    __OUTPUT__
    3 not in file 1

    FYI: This newsgroup is defunct. Try comp.lang.perl.misc in the future
    for better response.
     
    Jim Gibson, Dec 11, 2003
    #2
    1. Advertisements

  3. perldoc -q difference:
    "How do I compute the difference of two arrays? How do I compute the
    intersection of two arrays?"

    While the solution is written for arrays, it is trivial to modify it for
    files.

    jue
     
    Jürgen Exner, Dec 12, 2003
    #3
  4. If you're on a unix-like system, you can use the 'comm' utility for this.
     
    Eric J. Roode, Dec 12, 2003
    #4
  5. Jorgen Gustafsson, Dec 12, 2003
    #5
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.