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

Hey monks, I am not sure if I am asking this question at the right place but I am having issue with my file compare code in perl. I have two files -
File 1 - "/export/home/Tests/outputIS.txt"
The text that is in File 1:
IS Count: 1268706
File 2 - "/export/home/Tests/outputDB.txt"
The text that is in File 2:
IS Count: 1268706
use File::Compare; if (compare("/export/home/Tests/outputIS.txt","/export/home/Tests/outp +utDB.txt") == 0) { print "They're equal\n"; } else { print "Files are not equal\n"; }
Even though the files are exactly the same, it reports out "Files are not equal". Any help and suggestions would be appreciated! Thanks!

Replies are listed 'Best First'.
Re: File comparison
by frozenwithjoy (Priest) on Jul 17, 2012 at 17:37 UTC
    It is working for me with the same file content. Are you sure that there isn't a newline or space at the end of one, but not the other? You should try two things to verify that all is well with your script on your system: 1) compare a file to itself and 2) compare a file to an actual copy of itself. However, I suspect there is some invisible character that is causing the problem. On the command line, try diff file1 file2.
      Thanks for replying so fast. I tried on the command line and it doesn't show any differences there. If I compare both files to themselves, it works! And I checked both files again and they have the same number of characters, no extra lines. So any idea what else could be causing this problem?

        You've already determined the root cause of the problem was that you weren't closing the files before you were comparing them. But for future reference, there's the cmp utility.

        Believe it or not, there's a special case of two same text files for which diff will report no differences, but cmp will report a difference at the very first byte. Wanna know what it is? :-)

        UPDATE:  It's not made explicitly clear in perldoc File::Compare, but this core module implements the Unix cmp(1) functionality in Perl. This is stated in the README file.

        Very strange. Could you just try wc file1 file2 real quick as independent confirmation that they have the same # of characters/lines?
Re: File comparison
by ww (Archbishop) on Jul 17, 2012 at 17:42 UTC
    Your code works for me... with two files that are equal -- ie, identical.

    Check your files: does one have a trailing space, a newline or other byte that's not present in the other.

      I think I know what the problem is. I am creating both files in the same script above and then I have this code to compare. But if I put the comparison code in a different file, it works!
        Are their file handles closed before comparsion?
        Sorry if my advice was wrong.
Re: File comparison
by cheekuperl (Monk) on Jul 18, 2012 at 10:47 UTC