这是一个小问题,我希望你能帮助我。我的代码可能是垃圾。例如,我有一个文件,其中唯一的语句是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之外的其他名称
时,并不是说文件中不存在该名称答案 0 :(得分:1)
有几个问题:
你没有chomp
$ c。文件名最后包含换行符。
您使用open
的2参数形式,但不测试第二个参数。这是一个安全问题:如果用户输入包含>
或|
,您知道会发生什么吗?
您使用==
来比较字符串。字符串相等性使用eq
进行测试,但==
测试数字。
此外,你不想知道“Sam”是否等于“John是Sam的叔叔”。你想知道它是否是它的一部分。您可能需要使用index
或正则表达式来查找。
不要使用$a
作为变量的名称,它是特殊的(请参阅perlvar)。
答案 1 :(得分: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";
}