1

这是一个小问题,我希望你能帮助我。我的代码可能是垃圾。例如,我有一个文件,其中唯一的语句是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);

这是我到目前为止所做的事情,交集没有给出两个数组中常见的单词 uncle。该程序正在使用任何随机名称并打印它们。当我输入 John 和 Sam 以外的其他名称时,这并不是说文件中不存在该名称

4

2 回答 2

1

有几个问题:

  1. 你没有chomp$c。文件名末尾包含换行符。

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

  3. ==用来比较字符串。字符串相等性eq通过==测试数字进行测试。

  4. 此外,您不想知道“Sam”是否等于“John is the uncle of Sam”。你想知道它是否是它的一部分。您可能需要使用index正则表达式来找出答案。

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

于 2013-08-05T11:57:23.300 回答
0

不要尝试将字符串与==! 改用eq(等于)。你也没有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";
}
于 2013-08-05T12:07:20.000 回答