-->

Perl中读取文件和一个数组,找到共同的词(Perl read a file and an arra

2019-10-18 11:24发布

这是怎样的一个小问题,我希望你能帮助我。 我的代码可能是垃圾。 举个例子,我有一个文件,其中唯一的语句是John is the uncle of Sam 。 我的Perl脚本应该将文件内容复制到一个数组。 用户应该能够输入不同的名称如果这些名称在文件中提到的搜索。 应该有与像在节目“伯父伯母,母亲,父亲等”关系的数组。

#use warnings;
use Array::Utils qw(:all);

print "Please enter the name of the file\n";
my $c = <STDIN>;

open(NEW,$c) or die "The file cannot be opened";

@d = <NEW>;
print @d, "\n";

@g = qw(aunt uncle father);

chomp @d;
chomp @g;
my $e;
my $f;


print "Please enter the name of the first person\n";
my $a = <STDIN>;
print "Please enter the name of the second person\n";
my $b = <STDIN>;

my @isect = intersect(@g, @d);

print @isect;


foreach(@d)
    {
        if ($a == $_)
            {
                $e = $a;
            }
        else
            {
                print "The first person is not mentioned in the article";
                exit();
            }
        if ($b == $_)
            {
                $f = $b;
            }
        else
            {
                print "The second person is not mentioned in the article";
                exit();
            }
    }


print $e;
print $f;
close(NEW);

这是什么,我已经做了,到目前为止,该路口没有给这个词的叔叔是在两个数组常见的单词。 该计划采取任何随机名称进行打印。 这是不是说,当我进入比约翰和萨姆等不同名称的名称并不在文件中存在

Answer 1:

有几个问题:

  1. 你不chomp $ C。 该文件名包含在最后一个换行符。

  2. 您可以使用的2参数的形式open ,但不测试的第二个参数。 这是一个安全的问题:你知道,如果用户输入包含发生了什么>|

  3. 您可以使用==比较字符串。 字符串平等与测试eq ,虽然==测试号码。

  4. 此外,你不想知道的“萨姆”是否等于“约翰是山姆叔叔”。 你想知道它是否是它的一部分。 您可能需要使用index或正则表达式来了解一下。

  5. 不要使用$a作为变量的名称,它是特殊的(参见perlvar )。



Answer 2:

不要试图用比较字符串== ! 使用eq (等于)来代替。 你也didnt chomp您输入$a $ B`。 我认为这是你想要做什么:

#!/usr/bin/perl

use strict;
use warnings;

print "Please enter the name of the file\n";
my $c = <STDIN>;

open(NEW,$c) or die "The file cannot be opened";

my @d = <NEW>;
chomp @d;
my $e;
my $f;


print "Please enter the name of the first person\n";
my $aa = <STDIN>;
print "Please enter the name of the second person\n";
my $bb = <STDIN>;

chomp $aa;
chomp $bb;

my $pattern_a = quotemeta $aa;
my $pattern_b = quotemeta $bb;

foreach (@d){

    if ($_ =~ /$pattern_a/){
        $e = $aa;
    }
    elsif ($_ =~ /$pattern_b/){
        $f = $bb;
    }
}

close(NEW);


unless ($e){
    print "First person not mentionend\n";
}
unless ($f){
    print "Second person not mentioned\n";
}


文章来源: Perl read a file and an array and find common words