il-fox
il-fox

Reputation: 75

Perl <STDIN> not matching contents in an array

I have a file which consists of three names: daniel, elaine and victoria. If I search for daniel I get "you are not on the list". Could someone kindly point out where my mistake is? Thank you.

#!/usr/bin/perl 

#open file 
open(FILE, "names") or die("Unable to open file"); 

# read file into an array 
@data = <FILE>; 

# close file 
close(FILE); 

print "Enter name\n"; 
$entry = <STDIN>; 
chomp $entry; 

if (grep {$_ eq $entry} @data) 
{ 
print "You are on the list $entry"; 
} 
else 
{ 
print "Your are not on the list"; 
} 

Upvotes: 2

Views: 345

Answers (2)

Harry Barry
Harry Barry

Reputation: 194

change this

if (grep {$_ eq $entry} @data) 

to this

if (grep {$_ =~ m/^$entry\b/i} @data)

remove the i if you specifically want it to be case sensitive.

Upvotes: 2

gangabass
gangabass

Reputation: 10666

You need to chomp (remove new line character from the end of each string) data from the file too:

chomp @data;

if (grep {$_ eq $entry} @data) { 
    print "You are on the list $entry"; 
} else { 
    print "Your are not on the list"; 
} 

Upvotes: 8

Related Questions