First, one question: are your files guaranteed to be in the same order? If not, can you sort them (using for example the Unix sort utility) according to the same key(s) before you start? If yes, then you can build on the algorithm I have shown above, reading both files in parallel. Please let us know if you have any difficulty with this.

When dealing with this type of problem, I usually follow a two-step approach: first read the two files in parallel in order to extract the "orphans", i.e. lines which are in one file and not in the other in accordance with a comparison key. This produces two files without orphans (therefore having the same line keys and the same number of lines), which I can then easily compare for differences between the lines (for fields not part of the comparison key). This two-step approach is not necessary, it can be done in one go, but it usually makes it easier to process the data and deal with edge cases.

As for line endings, the easiest is probably to start by eliminating all line endings when reading the lines, to make the comparisons independent of line endings, and to add the line endings at the end, when outputting the result.

A simple instruction such as:

$line =~ s/[\r\s]+//g;
should remove any line ending, whether Windows or Unix (or Mac), from the $line string.


In reply to Re^5: Getting error when trying to compare two files by Laurent_R
in thread Getting error when trying to compare two files by adalamre

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.