Grep找到Perl数组中的项目 [英] Grep to find item in Perl array
本文介绍了Grep找到Perl数组中的项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
#!/ usr / bin / perl
@array =<> ;;
print输入你要匹配的单词\\\
;
chomp($ match =< STDIN>);
if(grep($ match,@array)){
printfound it\\\
;
解决方案
grep需要评估为真或假以表明是否匹配。所以它应该是:
#注意,grep返回一个列表,所以$匹配需要在括号内以获得
#实际值,否则$匹配将只包含匹配数
if(my($ matched)= grep $ _eq $ match,@array){
print找到它:$匹配\\\
;
$ / code>
如果您需要匹配很多不同的值,它可能也是值得您考虑将数据
数据放入散列
中,因为散列允许您高效地执行此操作,而无需
#将数组转换为散列值,数组元素作为散列键,值为1
my%hash = map {$ _ => 1} @array;
#检查散列是否包含$ match
if(defined $ hash {$ match}){
printfound it\\\
;
}
Every time I input something the code always tells me that it exists. But I know some of the inputs do not exist. What is wrong?
#!/usr/bin/perl
@array = <>;
print "Enter the word you what to match\n";
chomp($match = <STDIN>);
if (grep($match, @array)) {
print "found it\n";
}
解决方案
The first arg that you give to grep needs to evaluate as true or false to indicate whether there was a match. So it should be:
# 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";
}
If you need to match on a lot of different values, it might also be worth for you to consider putting the array
data into a hash
, since hashes allow you to do this efficiently without having to iterate through the list.
# 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";
}
这篇关于Grep找到Perl数组中的项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文