in reply to comparing 2 files problem

How about

open(FILE1, '<file1.txt') or die("Cannot open first file: $!.\n"); open(FILE2, '<file2.txt') or die("Cannot open second file: $!.\n"); # Load up the second file into a hash, # where each line of the file is a key. %file2 = map { $_ => 1 } <FILE2>; while (<FILE1>) { if ($file2{$_}) { print("Found $_"); } else { print("Didn't find $_"); } } __END__ file1.txt ========= qwerty snakegod ebrine tarot file2.txt ========= snakegod ordo rosae moriatur tarot wrath of hibernia output ====== Didn't find qwerty Found snakegod Didn't find ebrine Found tarot

Replies are listed 'Best First'.
Re^2: comparing 2 files problem
by ikegami (Patriarch) on Sep 07, 2004 at 18:52 UTC
    # A version that also checks for lines in file2 that are not in file1: open(FILE1, '<file1.txt') or die("Cannot open first file: $!.\n"); open(FILE2, '<file2.txt') or die("Cannot open second file: $!.\n"); %file1 = map { $_ => 1 } <FILE1>; %file2 = map { $_ => 1 } <FILE2>; foreach (keys(%file1)) { if ($file2{$_}) { print("Found in both files: $_"); } else { print("Found only in first file: $_"); } } foreach (keys(%file2)) { unless ($file1{$_}) { print("Found only in second file: $_"); } }
      # This version adds difference counts: open(FILE1, '<file1.txt') or die("Cannot open first file: $!.\n"); open(FILE2, '<file2.txt') or die("Cannot open second file: $!.\n"); $file1{$_}++ while (<FILE1>); $file2{$_}++ while (<FILE2>); foreach (keys(%file1)) { if ($file2{$_}) { $diff = $file2{$_} - $file1{$_}; if ($diff) { if ($diff < 0) { print("Found in first file $diff times more than in second + file: $_"); } else { print("Found in second file $diff times more than in first + file: $_"); } } else { print("Found in both files an equal number of times: $_"); } } else { print("Found only in first file ($file1{$_} times): $_"); } } foreach (keys(%file2)) { unless ($file1{$_}) { print("Found only in second file ($file2{$_} times): $_"); } }