加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

Grep在perl数组中查找项目

发布时间:2020-12-15 21:13:03 所属栏目:大数据 来源:网络整理
导读:每当我输入代码总是告诉我它存在的东西.但我知道一些输入不存在.你能帮助我们什么是错的? #!/usr/bin/perl@array = ; print "Enter the word you what to matchn";chomp($match = STDIN);if (grep($match,@array)) { print "found itn";} 解决方法 您给gr
每当我输入代码总是告诉我它存在的东西.但我知道一些输入不存在.你能帮助我们什么是错的?
#!/usr/bin/perl

@array = <>;    
print "Enter the word you what to matchn";
chomp($match = <STDIN>);

if (grep($match,@array)) {
    print "found itn";
}

解决方法

您给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: $matchedn";
}

如果您需要匹配很多不同的值,那么您也可以考虑将数组数据放入散列中,因为哈希允许您有效地执行此操作,而无需遍历列表.

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读