darkmoon has asked for the wisdom of the Perl Monks concerning the following question:
Hi, I am new to perl. I have two files, I need to do comparison to find out the matching and non-matching data. I got two problems now: Question 1: one of my hashes can only capture the 2nd row of the 'num', i tried to use `push @{hash1{name1}},$x1,$y1,$x2,$y2` , but it still returning the 2nd row of the 'num'.
File1 :File2:name foo num 111 222 333 444 name jack num 999 111 222 333 num 333 444 555 777
This is my code:name jack num 999 111 222 333 num 333 444 555 777 name foo num 666 222 333 444
My output:#!/usr/bin/perl use strict; use warnings; use Data::Dumper; my $input1=$ARGV[0]; my $input2=$ARGV[1]; my %hash1; my %hash2; my $name1; my $name2; my $x1; my $x2; my $y2; my $y1; open my $fh1,'<', $input1 or die "Cannot open file : $!\n"; while (<$fh1>) { chomp; if(/^name\s+(\S+)/) { $name1 = $1; } if(/^num\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)/) { $x1 = $1; $y1 = $2; $x2 = $3; $y2 = $4; } $hash1{$name1}=[$x1,$y1,$x2,$y2]; } close $fh1; print Dumper (\%hash1); open my $fh2,'<', $input2 or die "Cannot open file : $!\n"; while (<$fh2>) { chomp; if(/^name\s+(\S+)/) { $name2 = $1; } if(/^num\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)/) { $x1 = $1; $y1 = $2; $x2 = $3; $y2 = $4; } $hash2{$name2}=[$x1,$y1,$x2,$y2]; } close $fh2; print Dumper (\%hash2);
My expected Output:$VAR1 = { 'jack' => [ '333', '444', '555', '777' ], 'foo' => [ '111', '222', '333', '444' ] }; $VAR1 = { 'jack' => [ '333', '444', '555', '777' ], 'foo' => [ '666', '222', '333', '444' ] };
$VAR1 = { 'jack' => [ '999', '111', '222', '333', '333', '444', '555', '777' ], 'foo' => [ '111', '222', '333', '444' ] }; $VAR1 = { 'jack' => [ '999', '111', '222', '333', '333', '444', '555', '777' ], 'foo' => [ '666', '222', '333', '444' ] };
Question 2: I tried to use this foreach loop to do the matching of keys and values and print out in a table format. I tried this :
print "\t\tFIle1\t\t\t\t\tFile2\n"; print "Name\tX1\tY1\tX2\tY2\t\t\tX1\tY1\tX2\tY2\n"; foreach my $k1(keys %hash1) { foreach my $k2(keys %hash2) { if($hash1{$name} eq $hash2{$name2}) { if($hash1{$x1}{$y1}{$x2}{$y2} == $hash2 +{$x1}{$y1}{$x2}{$y2}) { print "$name\$x1\$y1\$x +2\$y2\n"; } } } }
but Im getting the header only.
my desired output for matching :File1 File2 Name X1 Y1 X2 Y2 X1 Y1 X2 Y2
Any help?File1 File2 Name x1 y1 x2 y2 x1 y1 x2 y2 jack 999 111 222 333 999 111 222 333 333 444 555 777 333 444 555 777
|
|---|