【问题标题】:Perl <STDIN> not matching contents in an arrayPerl <STDIN> 与数组中的内容不匹配
【发布时间】:2013-05-28 11:08:17
【问题描述】:

我有一个包含三个名字的文件: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"; 
} 

【问题讨论】:

    标签: perl filehandle


    【解决方案1】:

    你也需要chomp(从每个字符串的末尾删除换行符)文件中的数据:

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

    【讨论】:

    • 为此 +1。我不知道chomp @array 会从所有条目中删除最后一个字符。我之前用过map{chomp;}@array
    【解决方案2】:

    改变这个

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

    到这里

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

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

    【讨论】:

    • @Harry_Barry victoriavic 将在这里同等匹配。
    • @mpapec 对不起,我的错,已修复。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-15
    • 1970-01-01
    • 2013-02-26
    • 2022-12-05
    • 2021-02-22
    • 1970-01-01
    相关资源
    最近更新 更多