0

我有一行保存在我读入数组的文本文档中。这条线是

John is the uncle of Sam

我有另一个包含单词auntuncle的数组father。我希望两个数组都比较和输出叔叔(不区分大小写)。我不知道我做错了什么。我使用List::CompareArray::Utils qw(:all)等。有人可以给我一个工作代码。我只需要比较部分。

这就是我到目前为止所做的一切。

#!/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;
4

2 回答 2

2

最简单的:

for my $line (@file) {
    for my $word (@words) {
        if ($line =~ /\Q$word/i) {
            print "$word is found in '$line'";
        }
    }
}

您可以将单词合并到一个正则表达式中,这样您就可以跳过单词的循环:

my $rx = join '|', map quotemeta, @words;
for my $line (@file) {
    if ($line =~ /$rx/i) {
        print "Match found";
    }
}

或使用grep

my @found = grep /$rx/i, @file;
于 2013-08-06T11:47:16.450 回答
2

您有一个包含 3 个元素的数组(姑姑姑姑),而您从文件中读取的数组只包含一个元素(!“John 是 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";
        }
    }
}

如果您想将该行的每个单词都放在一个数组中,您应该split在该行上使用,例如,@words_from_line = split(" ",$line);然后您会得到一个包含单词的数组,您可以将其与另一个单词进行比较。

于 2013-08-06T11:53:40.813 回答