Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation

Re: Comparing strings from different files

by marinersk (Priest)
on Oct 08, 2013 at 15:38 UTC ( #1057427=note: print w/replies, xml ) Need Help??

in reply to Comparing strings from different files

If the files are not huge (i.e., one of them will fit in memory), I would go with the approach specified by hippo. Read file #1 into hash, then compare each line in file #2 to the hash.

If the files are too big for this, a slight modification: Read file #1 and store the seek (or tell) locations in the hash. Then compare each line in file #2 to the corresponding line in file #1, using your hash as a shortcut way to go straight to that line.

Update: Sample of first option:

#!/usr/bin/perl use strict; use warnings; my %FileInfo1 = (); my ($inputFilename1, $inputFilename2, @otherParameters) = @ARGV; # Read File 1 to Hash open INPUT_FILE1, '<', $inputFilename1; while (my $inputBuffer1 = <INPUT_FILE1>) { chomp $inputBuffer1; my ($key, $data) = split /\|/, $inputBuffer1, 2; $FileInfo1{$key} = $data; } close INPUT_FILE1; # Read File 2 and Compare open INPUT_FILE2, '<', $inputFilename2; while (my $inputBuffer2 = <INPUT_FILE2>) { chomp $inputBuffer2; my ($key, $data) = split /\|/, $inputBuffer2, 2; if (!defined $FileInfo1{$key}) { print "$key not found in $inputFilename1\n"; } elsif ($FileInfo1{$key} ne $data) { print "$key data does not match\n"; delete $FileInfo1{$key}; } else { print "$key - OK\n"; delete $FileInfo1{$key}; } } close INPUT_FILE2; foreach my $leftoverKey (keys %FileInfo1) { print "$leftoverKey not found in $inputFilename2\n"; } exit; __END__ C:\Steve\Dev\PerlMonks\P-2013-10-08@1245-TwoFile-Keyed-Compare>type te +st*.dat test1.dat A001|Steve|45 A002|George|32 A003|Alice|24 test2.dat A001|Steve|45 A003|Alice|23 A004|Mike|48 C:\Steve\Dev\PerlMonks\P-2013-10-08@1245-TwoFile-Keyed-Compare>perl cm test1.dat test2.dat A001 - OK A003 data does not match A004 not found in test1.dat A002 not found in test2.dat

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1057427]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others taking refuge in the Monastery: (4)
As of 2018-01-16 18:29 GMT
Find Nodes?
    Voting Booth?
    How did you see in the new year?

    Results (187 votes). Check out past polls.