I have two text files.
The first one has a list of words, like the following:
File 1.txt
Laura
Samuel
Gerry
Peter
Maggie
The second one has paragraphs on it. For example
File2.txt
Laura
is
about
to
meet
Gerry
and
is
planning
to
take
Peter
along
All I want the program to do is look for common words and print MATCH
beside the matching words in File2.txt
or to a third output file.
So the desired output should look like this.
Laura | MATCH
is
about
to
meet
Gerry | MATCH
and
is
planning
to
take
Peter | MATCH
along
I have tried the following code, however I am not getting the desired output.
use warnings;
use strict;
use Data::Dumper;
my $result = { };
my $first_file = shift || 'File1.txt';
my $second_file = shift || 'File2.txt';
my $output = 'output2.txt';
open my $a_fh, '<', $first_file or die "$first_file: $!";
open my $b_fh, '<', $second_file or die "$second_file: $!";
open( OUTPUT, '>' . $output ) or die "Cannot create $output.
";
while ( <$a_fh> ) {
chomp;
next if /^$/;
$result->{$_}++;
}
while ( <$b_fh> ) {
chomp;
next if /^$/;
if ( $result->{$_} ) {
delete $result->{$_};
$result->{ join " |" => $_, "MATCH" }++;
}
else {
$result->{$_}++;
}
}
{
$Data::Dumper::Sortkeys = 0;
print OUTPUT Dumper $result;
}
But the output that I am getting is like this.
Laura | MATCH
Samuel | MATCH
take
Maggie | MATCH
Laura
about
to
Gerry
meet
Gerry | MATCH
and
is
Maggie |MATCH
planning
to
Peter |MATCH
take
Peter |MATCH
The output is not in a paragraph format, nor is it printing MATCH
for all matches.
Please advise.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…