【问题标题】:Output common array elements输出公共数组元素
【发布时间】:2013-08-07 09:38:07
【问题描述】:

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

John is the uncle of Sam

我有另一个数组,其中包含单词auntunclefather。我希望两个数组都比较和输出叔叔(不区分大小写)。我不知道我做错了什么。我使用了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;

【问题讨论】:

  • 假设整个代码在这里:link
  • 是的。整件事只会让人感到困惑,这就是我拆分它的原因。
  • 请使用 3-arg open open(NEW,'&lt;',$c)。您还应该考虑使用词法文件句柄open( my $new_fh, '&lt;', $c )my @d = &lt;$new_fh&gt;

标签: arrays perl compare


【解决方案1】:

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

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

【讨论】:

    【解决方案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;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多