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"; 
} 

2 Answers 2

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"; 
} 
Sign up to request clarification or add additional context in comments.

1 Comment

+1 for this. I didn't know that chomp @array removes the last char from all entries. I used map{chomp;}@array before.
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.

2 Comments

@Harry_Barry victoria and vic will match equally here.
@mpapec sorry my bad, fixed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.