Search code examples
arraysperlintersectionwords

Perl read a file and an array and find common words


This is kind of a small issue and I hope you are able to help me. My code is probably rubbish. For an example, I have a file in which the only statement is John is the uncle of Sam. My Perl script should copy the file contents into an array. User should be able to input different names and search if those names are mentioned in the file. There should be an array with relationships like "uncle aunt, mother, father etc" in the program.

#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);

This is something that I have done so far, the intersection is not giving the word uncle which is the word common in both arrays. The program is taking any random name and printing them. It is not saying that the name doesn't exist in the file when I enter a different name other than John and Sam


Solution

  • There are several problems:

    1. You do not chomp $c. The filename contains a newline at the end.

    2. You use the 2-argument form of open, but do not test the second argument. This is a security problem: do you know what happens if the user input contains > or |?

    3. You use == to compare strings. String equality is tested with eq, though, == tests numbers.

    4. Moreover, you do not want to know whether "Sam" equals to "John is the uncle of Sam". You want to know whether it is a part of it. You might need to use index or regular expressions to find out.

    5. Do not use $a as the name of a variable, it is special (see perlvar).