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

If u have a file</>

FILE A

Beck 2

Ron 4

Test 5

Zid 6

FILE B

Ron 3

Zid 15

Steve 5

Beck 6

check 4

Test 6

So output shud be while comparing two files

Beck 2 6

Ron 4 3

Test 5 6

Zid 6 15

#!/usr/bin/perl use strict; use warnings; open(my $fh1,"$ARGV[0]") or die "Unable to open file1:$!"; my @array1=<$fh1>; close($fh1); chomp @array1; my %hash; @hash{@array1} = undef; my $pattern = join ('|', @array1); open(my $fh2,"$ARGV[1]") or die "Unable to open file2:$!";; for my $line (<$fh2>) { chomp $line; if ($line =~ /($pattern)/) { } } close($fh2);
what can be print command line to get this output? Thanks

Replies are listed 'Best First'.
Re: matching two files and print together the inputs
by Corion (Patriarch) on May 26, 2010 at 19:41 UTC
Re: matching two files and print together the inputs
by ww (Archbishop) on May 26, 2010 at 20:58 UTC
Re: matching two files and print together the inputs
by kennethk (Abbot) on May 26, 2010 at 19:48 UTC
    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.

Re: matching two files and print together the inputs
by suhailck (Friar) on May 27, 2010 at 04:47 UTC
    An awk solution

    awk 'NR==FNR{a[$1]=$2;next}$1 in a{print $1,a[$1],$2} ' fileA fileB

    ~suhail