By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
438,373 Members | 1,984 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 438,373 IT Pros & Developers. It's quick & easy.

comparing two files

P: 1

I am not brilliant at perl (pretty rubbish) and would like to compare the contents of two files preferably with an output file of all the entries which are the same and also a count of how many entries are the same.

So far I have a bit of code which takes two files and saves them to arrays - not sure if thats the best approach, my code so far is below but as yet doesn't get down to the important part as I haven't a scooby as how to achieve this (have tried a few things and they have not worked)

I want to be able to compare text files with one "tag" name per line
(have so far been using simple files: File1.txt - A,B,C,D,E,F,G,H AND File2.txt - I,J,F,A,B,K,C,Y,Z)

Expand|Select|Wrap|Line Numbers
  2. #!/usr/bin/perl;
  3. use warnings;
  4. use strict;
  7. #global variables for the program
  8. my $file1 = "";
  9. my $file2 = "";
  10. my $line1 = "";
  11. my @tag1;
  12. my $line2 = "";
  13. my @tag2;
  14. my $same = 0;
  15. my $tag1 = "";
  16. my $tag2 = "";
  19. #get user to input a file
  20. print "Please type in a file name for comparison, and press enter\n";
  21. #save file to $file1 variable
  22. $file1 = <STDIN>;
  23. #remove new line from input
  24. chomp $file1;
  25. #open file, if file does not exist end 
  26. open (FILE1, "$file1") or die "Can't find file $file1";
  28. #save file into array @tag1
  29. while ($line1 = <FILE1>){
  30. #read in each line from file and copy to $line, each new line saved to array @names
  31.     push (@tag1,$line1);
  32.     }
  34. #Get user to enter an additional file to compare to
  35. print "Thank you\nPlease enter a second file for the comparison\n";
  36. #Save file to $file2
  37. $file2 = <STDIN>;
  38. #remove new line from input
  39. chomp $file2;
  40. #open file, if it does not exist end program
  41. open (FILE2, "$file2") or die "Can't find file $file2";
  43. #save file into array @tag2
  44. while ($line2 = <FILE2>){
  45. #read in each line from file and copy to $line, each new line saved to array @names
  46.     push (@tag2,$line2);
  47.     }
Thank you in advance!
Jan 27 '10 #1
Share this Question
Share on Google+
2 Replies

Expert 5K+
P: 5,000
Why reinvent the wheel?
Jan 27 '10 #2

Expert Mod 2.5K+
P: 3,503
Or you could even use File::Compare. Either way, there are better ways to do it.

Also, if you post code, PLEASE use code tags!


Jan 28 '10 #3

Post your reply

Sign in to post your reply or Sign up for a free account.