2

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"; 
} 
il-fox
  • 75
  • 2
  • 8

2 Answers2

8

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"; 
} 
gangabass
  • 10,607
  • 2
  • 23
  • 35
  • +1 for this. I didn't know that `chomp @array` removes the last char from all entries. I used `map{chomp;}@array` before. – Demnogonis May 28 '13 at 11:56
2

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.

Harry Barry
  • 194
  • 7