Although you could to it with a single pass, I would recommend breaking this into three steps:
  1. Read file 1 and store the contents in a hash
  2. Read file 2 and store the contents in a second hash
  3. Compare the hash keys and output keys that are present in both files

An algorithm for the last step is outlined in a FAQ: How do I compute the difference of two arrays? How do I compute the intersection of two arrays?. I would do something along the lines of:

#!/usr/bin/perl use strict; use warnings; open(my $fh1, '<', "$ARGV[0]") or die "Unable to open $ARGV[0]:$!"; my %hash1; for (<$fh1>) { chomp; my ($key,$value) = split /\s+/, $_, 2; $hash1{$key} = $value; } open(my $fh2, '<', "$ARGV[1]") or die "Unable to open $ARGV[1]:$!"; my %hash2; for (<$fh2>) { chomp; my ($key,$value) = split /\s+/, $_, 2; $hash2{$key} = $value; } for my $key (keys %hash1) { next unless exists $hash2{$key}; print "$key $hash1{$key} $hash2{$key}\n"; }

Note the addition of '<' to your open statements - this is an important habit to get into for security reasons. Also note that wrapping your input file contents in <code> tags can be just as important as wrapping your code in them.


In reply to Re: matching two files and print together the inputs by kennethk
in thread matching two files and print together the inputs by vis1982

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.