Perl <stdin>不匹配数组</stdin>中的内容

时间:2013-05-28 11:08:17

标签: perl filehandle

我有一个由三个名字组成的文件:daniel,elaine和victoria。如果我搜索丹尼尔,我会得到“你不在名单上”。有人可以指出我的错误在哪里吗?谢谢。

#!/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 个答案:

答案 0 :(得分:8)

您还需要chomp(从每个字符串末尾删除新行字符)数据:

chomp @data;

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

答案 1 :(得分:2)

更改此

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

到这个

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

如果您特别希望它区分大小写,请删除i。

相关问题