每当我输入代码总是告诉我它存在的东西.但我知道一些输入不存在.你能帮助我们什么是错的?
#!/usr/bin/perl @array = <>; print "Enter the word you what to match\n"; chomp($match = <STDIN>); if (grep($match,@array)) { print "found it\n"; }
解决方法
您给grep的第一个参数需要评估为true或false来指示是否有匹配.所以应该是:
# note that grep returns a list,so $matched needs to be in brackets to get the # actual value,otherwise $matched will just contain the number of matches if (my ($matched) = grep $_ eq $match,@array) { print "found it: $matched\n"; }
如果您需要匹配很多不同的值,那么您也可以考虑将数组数据放入散列中,因为哈希允许您有效地执行此操作,而无需遍历列表.
# convert array to a hash with the array elements as the hash keys and the values are simply 1 my %hash = map {$_ => 1} @array; # check if the hash contains $match if (defined $hash{$match}) { print "found it\n"; }