Reputation: 203
I have a line saved in a text document which I read into an array. The line is
John is the uncle of Sam
I have another array that contains the words aunt
, uncle
and father
. I would like both the arrays to compare and output the uncle (case insensitive). I don't know what I am doing wrong. I used List::Compare, Array::Utils qw(:all) etc. Could someone give me a working code. I just need the comparison part.
This is all I have done so far.
#!/usr/bin/env perl
use strict;
use warnings;
use Array::Utils qw':all';
print "Please enter the name of the file\n";
my $c = <STDIN>;
chomp($c);
open(NEW,$c) or die "The file cannot be opened";
my @d = <NEW>;
my @g = qw'aunt uncle father';
chomp(@g);
chomp(@d);
my @isect = intersect(@g, @d);
print @isect;
Upvotes: 0
Views: 170
Reputation: 1256
You have one array that contains 3 elements (aunt uncle sister) and the one that you read from the file only contains one (! "John is the uncle of Sam"):
#!/usr/bin/perl
use strict;
use warnings;
my @searchwords = qw(aunt uncle sister);
my @article = ("John is the uncle of Sam",);
foreach my $searchword (@searchwords){
my $pattern = quotemeta $searchword;
foreach my $line (@article){
if ($line =~ /$pattern/i){
# //i makes the match case insensitive
print $searchword . " matched in " . $line . "\n";
}
}
}
If you want to have every word of that line in an array you should use split
on the line like in @words_from_line = split(" ",$line);
Then you get an array with words which you can compare to the other one.
Upvotes: 2
Reputation: 67900
At its simplest:
for my $line (@file) {
for my $word (@words) {
if ($line =~ /\Q$word/i) {
print "$word is found in '$line'";
}
}
}
You can merge the words into a regex, which will allow you to skip the looping over words:
my $rx = join '|', map quotemeta, @words;
for my $line (@file) {
if ($line =~ /$rx/i) {
print "Match found";
}
}
Or using grep
:
my @found = grep /$rx/i, @file;
Upvotes: 2