簡體   English   中英

Perl讀取文件和數組並找到常用詞

[英]Perl read a file and an array and find common words

這是一個小問題,希望您能為我提供幫助。 我的代碼可能是垃圾。 例如,我有一個文件,其中唯一的陳述是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);

到目前為止,這是我做過的事情,但交集沒有給出叔叔這個單詞,這是兩個數組中的通用單詞。 該程序將使用任何隨機名稱並進行打印。 當我輸入除John和Sam以外的其他名稱時,並不是說文件中不存在該名稱。

有幾個問題:

  1. 您不chomp $ c。 文件名末尾包含換行符。

  2. 您使用open的2參數形式,但不要測試第二個參數。 這是一個安全問題:您知道用戶輸入包含>|時會發生什么情況|

  3. 您使用==比較字符串。 字符串相等性使用eq進行測試,但是==測試數字。

  4. 而且,您不想知道“ Sam”是否等於“ John是Sam的叔叔”。 您想知道它是否是其中的一部分。 您可能需要使用index或正則表達式來查找。

  5. 不要將$a用作變量的名稱,這是特殊的(請參閱perlvar )。

不要嘗試將字符串與==進行比較! 請改用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";
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM